Removal of element from list while traversing causes the next element to be skipped

Berteun Damman berteun at NO_SPAMdds.nl
Tue Jan 29 18:03:33 CET 2008


On Tue, 29 Jan 2008 16:34:17 GMT, William McBrine <wmcbrine at users.sf.net> wrote:
> Look at this -- from Python 2.5.1:
>
>>>> a = [1, 2, 3, 4, 5]
>>>> for x in a:
> ...     if x == 3:
> ...         a.remove(x)
> ...     print x
> ... 
> 1
> 2
> 3
> 5
>>>> a
> [1, 2, 4, 5]

You have to iterate over a copy of 'a', so for x in a[:]. Modifying a
list while iterating over is a recipe for problems. (As it is in many
other programming languages.)

Berteun



More information about the Python-list mailing list