recognizing empty iterators

Bengt Richter bokr at oz.net
Tue Jul 22 02:15:48 CEST 2003


On 21 Jul 2003 07:26:15 -0700, mis6 at pitt.edu (Michele Simionato) wrote:

>After a recent thread on .endswith, I have been thinking about iterators.
>I realized that I don't know a satisfactory way to check if an
>iterator is empty. In other words I am looking for an
>"isempty" function to use in "if" statements such as
>
>if isempty(iterator):
>   do_something()
>
>without side effects. Here are some unsatisfactory ways of implementing
>"isempty":
>
>#1: converting to a list or tuple
>def isempty(iterator):
>    return not list(iterator)
>
>Easy, but one has to create the entire list, thus defecting the basic
>purpose of the iterator, i.e. lazy evaluation.
>
>#2: checking for StopIteration
>def isempty(iterator):
>    try:
>        iterator.next()
>    except StopIteration:
>        return True
>    else:
>        return False
>
>This works, for instance
>
>print isempty(iter([]))
>
>gives True and 
>
>it=iter([1,2,3])
>print isempty(it)
>
>gives False. However, there is a side effect: after the check, the
>iterator has advanced of one step and now "it.next()" gives 2, not 1. 
>In order this to work without side effects, I should be able to restart 
>the iterator from the beginning, but I don't know how to do that.
>Is it possible?
>
>#3: comparing with the empty iterator
>
>emptyiterator=iter([])
>
>it=iter([])
>
>if it == emptyiterator: print 'Ok!'
>
>This simply doesn't work.
>
>I wonder if the itertools module should contain a function to check for
>empty iterators, thus simplifying my life ;) Of course, I may well be
>missing something obvious, if so, please enlighten me.
>
If iterators had a .peek() method for 1-item lookahead, maybe that would
be easy to implement. If empty, it could raise StopIteration, and otherwise
return what next() would return, without disturbing the state w.r.t. next().

Alternatively, it could return [nextitem] vs [] if at the end
(without raising StopIteration).

Regards,
Bengt Richter




More information about the Python-list mailing list