I just simply want to remove all the elements in the python list one by one by remove()
method, but find out that does not work. I run the code below:
a=[1,2,3]
for i in a:
a.remove(i)
print a
and it shows
[2]
I just simply want to remove all the elements in the python list one by one by remove()
method, but find out that does not work. I run the code below:
a=[1,2,3]
for i in a:
a.remove(i)
print a
and it shows
[2]
What's happening there is that you are changing a list while you iterate over it, but the iterator on that list will not get updated with your changes. So as you delete the first element (index = 0
) in the first iteration, the second one (index = 1
) becomes now the first (index = 0
), but the iterator will next return the second (index = 1
) element instead of returning (again) the first one that has changed and has been skipped. Step by step:
Iterator starts at index 0, which is element 1
. List is [1, 2, 3]
. You remove that element and end up with [2, 3]
.
Iterator moves to index 1, which is element 3
(note 2 has been skipped). You remove that element and end up with [2]
.
Iterator moves to index 2, which doesn't exist, so iteration is over.