+ 1

Why does remove method doesnot remove last element?

I wanted to remove the first and last element of the list.so I used a.remove(a[0]) and a.remove(a[l-1]) where l is the length of the list.I then used pop method to remove last element and it worked.But I need to know the reason why remove method didnt work

26th Dec 2018, 10:23 AM
Josephine Gitanjali
Josephine Gitanjali - avatar
2 ответов
+ 4
1. remove() does two things: it finds the match and then remove the -->FIRST<-- matched element. So you are right in putting the value of the element you want to remove into the list method remove(). But if the same value appears also at an earlier position, the earlier element will be removed instead. Demo: https://code.sololearn.com/cIU0H8LV8C37/?ref=app Reference: https://www.programiz.com/JUMP_LINK__&&__python__&&__JUMP_LINK-programming/methods/list/remove 2. If last element only once, another possible reason that your remove fail is the sequence: l = len(a) a.remove(a[0]) #length changed a.remove(a[l-1]) #Error Either swap line 1 2 or swap line 2 3 can solve. 3. Note To access last element, no need a[l-1], just a[-1] is ok. 4. On the other hand, pop() can be used without argument or with the index. Without index, the last element is removed. With index, the indexed element is removed. Demoes: https://code.sololearn.com/c4BgVGCuw16N/?ref=app https://code.sololearn.com/cFYtswM82xLF/?ref=app
26th Dec 2018, 10:29 AM
Gordon
Gordon - avatar
+ 1
You were right. Thank you 😍
27th Dec 2018, 7:20 AM
Josephine Gitanjali
Josephine Gitanjali - avatar