Iterators membership testing

Tim Chase python.list at
Sun Aug 9 15:09:51 CEST 2015

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)

The addition of any/all initially struck me as a "why?! this is so
easy to write in-line" moment, only to find myself using them all()
the time. :-) The code-intention becomes so much clearer.  Even
back-ported them to 2.4 code that I maintain.


More information about the Python-list mailing list