Expression can be simplified on list

Chris Angelico rosuav at gmail.com
Thu Sep 29 05:19:26 EDT 2016


On Thu, Sep 29, 2016 at 6:45 PM, Jussi Piitulainen
<jussi.piitulainen at helsinki.fi> wrote:
> What do you say about things like iterators and generators? I'd say they
> are containers, but they count as true even when they are empty.
>
> bool(x for x in [3,1] if x in [2,7]) # True
> list(x for x in [3,1] if x in [2,7]) # []
>
> I think the abstraction really leaks on these things.

The problem is that there is no safe way to probe an iterator for
emptiness other than to attempt to consume a value from it. How do you
know if you're at the EOF of stdin? You ask the user to enter
something, and see if s/he presses Ctrl-D (or Ctrl-Z). Until you wait
on the user, EOF hasn't necessarily even happened yet.

An iterator is not a container, but in many contexts, it can be
treated as one. Truthiness is simply not one of those contexts, for
reasons of extreme impracticality.

ChrisA



More information about the Python-list mailing list