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:40:10 CET 2008


On Tue, 29 Jan 2008 09:23:16 -0800 (PST), attn.steven.kuo at gmail.com
<attn.steven.kuo at gmail.com> wrote:
> If you're going to delete elements from
> a list while iterating over it, then do
> it in reverse order:

Why so hard? Reversing it that way creates a copy, so you might as
well do:
>>> a = [ 98, 99, 100 ]
>>> for i, x in enumerate(a[:]):
 ...     if x == 99: del(a[i])
 ...     print x

Berteun



More information about the Python-list mailing list