Generator

MRAB google at mrabarnett.plus.com
Sun Mar 22 09:54:05 EDT 2009


mattia wrote:
> Can you explain me this behaviour:
> 
>>>> s = [1,2,3,4,5]
>>>> g = (x for x in s)
>>>> next(g)
> 1
>>>> s
> [1, 2, 3, 4, 5]
>>>> del s[0]
>>>> s
> [2, 3, 4, 5]
>>>> next(g)
> 3
> 
> Why next(g) doesn't give me 2?
> 
First it yields s[0] (which is 1), then you delete s[1], then it yields
s[1] (which is now 3). It doesn't yield 2 because that's in now s[0],
and it's already yielded s[0].

In general you shouldn't modify what you're iterating over because the
behaviour depends on how it happens to be implemented.



More information about the Python-list mailing list