iterate over list while changing it

Torsten Mohr tmohr at s.netic.de
Thu Sep 24 16:32:53 EDT 2009


Hello,

a = [1, 2, 3, 4, 5, 6]

for i, x in enumerate(a):
    if x == 3:
        a.pop(i)
        continue

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

    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