iterate over list while changing it

Terry Reedy tjreedy at udel.edu
Thu Sep 24 17:03:58 EDT 2009


Torsten Mohr wrote:
> Hello,
> 
> a = [1, 2, 3, 4, 5, 6]
> 
> for i, x in enumerate(a):

If you change a list while iterating over, start at the tail.

...reversed(enumerate(a))


>     if x == 3:
>         a.pop(i)

  del a[i] # you already have the item

>         continue
> 
>     if x == 4:
>         a.push(88)

no such list method, which mean you did not run the above before 
posting. Boo!

> 
>     print "i", i, "x", x
> 
> I'd like to iterate over a list and change that list while iterating.
> I'd still like to work on all items in that list, which is not happening
> in the example above.
> The conditions in the example are not real but much more complex
> in reality.
> 
> Can anybody tell me how to do this?
> 
> 
> Thanks for any hints,
> Torsten.
> 
> 




More information about the Python-list mailing list