Iterators membership testing

Chris Angelico rosuav at gmail.com
Sun Aug 9 07:10:25 EDT 2015


On Sun, Aug 9, 2015 at 9:00 PM, Pierre Quentel <pierre.quentel at gmail.com> wrote:
>> The trap you're seeing here is that iterating over an iterator always
>> consumes it, but mentally, you're expecting this to be iterating over
>> a new instance of the same sequence.
>
> No, I just tried to apply what I read in the docs :
>
> 1. I have y = A(10) which is an instance of a class which does not define __contains__ but does define __iter__
>
> 2. The value z = 0 is produced while iterating over y.
>
> 3. The sentence "x in y is true if some value z with x == z is produced while iterating over y" lead me to think that "0 in y" would be true.

You're almost right. The significance here is that once you've
partially iterated over y, the value z will not be produced while
iterating over y - so *at that point in time*, y does not contain z.
Iterators (non-infinite ones, at least) shrink over time, so the set
of objects they contain will shrink.

ChrisA



More information about the Python-list mailing list