Home > Blockchain >  Python, list.remove() does not work right
Python, list.remove() does not work right

Time:09-07

Hello I am trying to remove first and last 2 element of my list. My list is: ['12','30','22','06','27','13','23','16','14','20','09','29','23']

and this is the code I am using:

dList.remove(dList[0])
dList.remove(dList[-1])
dList.remove(dList[-1])

It works right too many other list but in this list it returns:

['30', '22', '06', '27', '13', '16', '14', '20', '09', '29']

Instead of;

['30', '22', '06', '27', '13', '23', '16', '14', '20', '09',]

I noticed the last element is '23' and both '23' be removed but I don't know how to fix it. It should be work right because I remove first element, and last element, and last element again. I didn't use:

a = dList[0]
dList.remove(a)
a = dList[-1]
dList.remove(a)
a = dList[-1]
dList.remove(a)

CodePudding user response:

The remove() method removes the first matching element (which is passed as an argument) from the list.

You have 23 repeated twice.

If you want to remove index you can use del in your example.it would be:

del dList[-1]

CodePudding user response:

this should work

dList = dList[1:-2]

CodePudding user response:

Why not using pop to pop out the last element of the list?

last_element = dList.pop()
semilast_element = dList.pop()

You can even put the index of the element you want to pop

first_element = dList.pop(0)
second_element = dList.pop(0)

Always refer to the original documentation

CodePudding user response:

With:

dList = ['12','30','22','06','27','13','23','16','14','20','09','29','23']

...you could construct a new list with a slice (as previously suggested) like this:

dList = dList[1:-2]

...or you can do it in situ using pop() as follows:

dList.pop(0)
dList.pop()
dList.pop()
  • Related