Reputation: 9
I've been working on a project in Python, coding a little game that's basically the number version of mastermind. Anyway, I came across a bug in my program and I'm curious as to why this is:
I had a list, and when removing the last element of the list, the order of the remaining elements changed. For example:
myList = [4, 4, 5, 4]
myList.remove(myList[3])
The contents of the list were now [4, 5, 4]
instead of [4, 4, 5]
. This did not happen with most other combinations of numbers which is why I am confused. Also, if I instead use:
myList = myList[:-1]
This works and the contents are in the correct order... Does anyone know why removing the last element the first way didn't work in this case?
Upvotes: 0
Views: 132
Reputation: 32189
myList.remove(myList[3])
is the same as doing
myList.remove(4)
and remove always removes the first instance. You should try doing:
del a[-1]
or as mentioned by @Megalng
a.pop()
which also returns the removed element
Upvotes: 4