Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Python skip elements when I modify a list while iterating over it?

I'm currently developing a program in python and I just noticed that something was wrong with the foreach loop in the language, or maybe the list structure. I'll just give a generic example of my problem to simplify, since I get the same erroneous behavior on both my program and my generic example:

x = [1,2,2,2,2]

for i in x:
    x.remove(i)

print x        

Well, the problem here is simple, I though that this code was supposed to remove all elements from a list. Well, the problem is that after it's execution, I always get 2 remaining elements in the list.

What am I doing wrong? Thanks for all the help in advance.

Edit: I don't want to empty a list, this is just an example...

like image 896
rogeriopvl Avatar asked Apr 12 '09 20:04

rogeriopvl


People also ask

Can you modify list while iterating Python?

The general rule of thumb is that you don't modify a collection/array/list while iterating over it. Use a secondary list to store the items you want to act upon and execute that logic in a loop after your initial loop.

Can you modify a list while in a for loop?

To modify a list while iterating over it: Use a for loop to iterate over a copy of the list. On each iteration, check if a certain condition is met. If the condition is met, modify the list.


1 Answers

This is a well-documented behaviour in Python, that you aren't supposed to modify the list being iterated through. Try this instead:

for i in x[:]:
    x.remove(i)

The [:] returns a "slice" of x, which happens to contain all its elements, and is thus effectively a copy of x.

like image 88
Chris Jester-Young Avatar answered Sep 19 '22 15:09

Chris Jester-Young