recognizing empty iterators

Michele Simionato mis6 at pitt.edu
Thu Jul 24 23:06:55 CEST 2003


After some thinking, and having read the suggestion in this thread, 
I see that the source of my problem was the following: whereas an
empty list or an empty tuple has a truth value of False, an empty
iterator has a truth value of True. It is easy to fix, anyway, with
a function which works as "iter", but return an empty list (or tuple)
when the iterator is empty:

import itertools

def iter_(seq):
    i=iter(seq)
    try:
        first=i.next()
    except StopIteration:
        return []
    return itertools.chain([first],i) 

Maybe not very elegant, but it works:

it=iter_('xyz')
for c in it:
    print c

if iter_(it):
    print "non empty"
else:
    print "is empty"

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 ...


    Michele




More information about the Python-list mailing list