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]
1

1 Answer 1

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:

  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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much Danziger !!!
what is the alternative solution ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.