recognizing empty iterators

Delaney, Timothy C (Timothy) tdelaney at
Fri Jul 25 02:55:56 CEST 2003

> From: Michele Simionato [mailto:mis6 at]
> BTW, the fact that an empty iterator is True is somewhat strange,
> considering that [],() and "" are False; on the other hand, generic
> objects are True, so the point can be debated ...

It is impossible to know, in the general case, if an iterator is empty. The primary reason for this is that many iterators are destructive e.g. file iterators. A wrapper iterator can be used around a destructive iterator that caches information, but that's about the best you can do unless the iterator is resettable.

An iterator may in fact be conceptually empty at one instant, then the next instant not be empty...

All it is possible to know is if an iterator has been exhausted *for now* - and that is if it raises StopIteration. Technically this does not mean that the iterator is permanently exhausted - it could start returning values at a later date, but this would be very confusing to people ;)

Tim Delaney

More information about the Python-list mailing list