Expression can be simplified on list

MRAB python at mrabarnett.plus.com
Thu Sep 29 07:53:30 EDT 2016


On 2016-09-29 10:49, Steven D'Aprano wrote:
> On Thursday 29 September 2016 18:45, Jussi Piitulainen wrote:
[snip]
>> 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.
>
> No, they aren't containers, because they don't support membership testing or
> len(), as containers must.
>
> But I agree the abstraction leaks. We would like empty iterables (iterators and
> sequences) to be falsey, but the problem is, how do you know if an iterator is
> empty without consuming a value from it? Sequences and containers can be probed
> without consuming values, but iterators cannot be.
>
> So although you can use them in many of the same places that you might use a
> sequence or container, they aren't actually sequences or containers, and are
> better treated as something like a function. (Except instead of calling them,
> you pass them to next() to get the next value.)
>
> And what are functions? Why, they're *things*, of course, and hence *something*
> rather than nothing, even if they return None, or never return at all, or
> crash. And so even though it is inconvenient, nevertheless it is logical for
> iterators to always be truthy.
>
> However, if you had a peekable iterator where you can peek ahead to see if they
> are empty or not, then it might make sense to treat them as more like a
> sequence than a function. But arbitrary iterators do not support a peek()
> operation.
>
> Either way, the abstraction leaks a bit. Never mind -- welcome to life as a
> programmer.
>
What if an _exhausted_ iterator was falsey?




More information about the Python-list mailing list