On Thu, 29 Sep 2016 09:53 pm, MRAB wrote: > What if an _exhausted_ iterator was falsey?
The problem is that in general you can't tell if an iterator is exhausted until you attempt to advance it. So even if bool(iterator) returns True, the call to next() may raise StopIteration: def gen(): yield 1 it = gen() bool(it) # returns True next(it) # returns a value, as expected, exhausting the iterator bool(it) # still returns True even though its exhausted next(it) # raises StopIteration bool(it) # finally we know the iterator is exhausted Again, the problem is the lack of a way for the iterator to peek ahead and see whether or not there is anything remaining. *We* can see that it is exhausted by reading the source code and predicting what will happen on the subsequent call to next(), but the interpreter cannot do that. And sometimes not even we can predict the state of the iterator: def gen(): if random.random() < 0.5: yield 1 it = gen() Is it exhausted or not? -- Steve “Cheer up,” they said, “things could be worse.” So I cheered up, and sure enough, things got worse. -- https://mail.python.org/mailman/listinfo/python-list