Skip to content Skip to sidebar Skip to footer

Cannot Remove The Last Element Of A Python List

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.r

Solution 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.


Post a Comment for "Cannot Remove The Last Element Of A Python List"