Iterator, modify data in loop body

Chris Angelico rosuav at gmail.com
Sat Sep 13 02:22:14 EDT 2014


On Sat, Sep 13, 2014 at 4:09 PM, Michael Welle <mwe012008 at gmx.net> wrote:
> foo = [1,2,3,4]
> it = iter(foo)
>
> for e in it:
>     if e % 2 == 0:
>         x.append(e)

A better way to do this is with a list comprehension:

x = [e for e in foo if e %2 == 0]

Modifying something that you're iterating over is unspecified, I
believe. Certainly it's not a good idea.

ChrisA



More information about the Python-list mailing list