iterate over list while changing it

Rhodri James rhodri at wildebst.demon.co.uk
Thu Sep 24 18:20:16 EDT 2009


On Thu, 24 Sep 2009 21:32:53 +0100, Torsten Mohr <tmohr at s.netic.de> wrote:

> 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?

Generally, don't.  It's much less dangerous to create a new list as you
go.

new_a = []
for x in a:
   if x != 3:
     new_a.append(x)
   if x == 4:
     new_a.append(88)
     # or whatever you intended "push" to mean

If you weren't doing the insertion, you could have used a list
comprehension and neatened things up a bit.

-- 
Rhodri James *-* Wildebeest Herder to the Masses



More information about the Python-list mailing list