Iterators membership testing

Chris Angelico rosuav at gmail.com
Sun Aug 9 09:11:20 EDT 2015


On Sun, Aug 9, 2015 at 11:09 PM, Tim Chase <tim at thechases.com> wrote:
> On 2015-08-09 19:24, Chris Angelico wrote:
>> That's exactly right. The only way for the interpreter to handle
>> 'in' on an iterator is something like this:
>>
>> def contains(iter, obj):
>>     for val in iter:
>>         if val == obj: return True
>>     return False
>
> Which can nicely be written as
>
>   any(i == obj for obj in iter)

Indeed it can, although I'm not sure whether it'd just have been
another step in the explanation :) Whether or not that makes perfect
sense depends on the reader.

ChrisA



More information about the Python-list mailing list