1

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]
Mazdak
  • 105,000
  • 18
  • 159
  • 188
roland
  • 21
  • 3
  • It's a [common pitfall](http://stackoverflow.com/documentation/python/3553/common-pitfalls/949/changing-the-sequence-you-are-iterating-over#t=201608202137582428236) – Ohad Eytan Aug 20 '16 at 21:40

1 Answers1

1

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:

  1. Iterator starts at index 0, which is element 1. List is [1, 2, 3]. You remove that element and end up with [2, 3].

  2. Iterator moves to index 1, which is element 3 (note 2 has been skipped). You remove that element and end up with [2].

  3. Iterator moves to index 2, which doesn't exist, so iteration is over.

Danziger
  • 19,628
  • 4
  • 53
  • 83