empty lists vs empty generators

Michele Simionato michele.simionato at gmail.com
Tue May 3 23:41:46 EDT 2005


Andrea Griffini:

> Are you sure this is going to do the right thing ?

Argh! I missed these two lines from the documentation:

"""Note, once tee() has made a split, the original iterable should not
be used anywhere else; otherwise, the iterable could get advanced
without the tee objects being informed."""

Since the original iterator cannot be reused, we need an alternative
approach. Here is a possibility:

#<check.py>

import itertools

def check(it):
    it_copy1, it_copy2 = itertools.tee(it)
    try:
        it_copy2.next()
    except StopIteration:
        return None
    else:
        return it_copy1

#</check.py>

Here a few examples of usage:

>>> from check import check

>>> it0 = iter([])
>>> print check(it0) # empty iterator, returns None
None

>>> it1 = iter([1])
>>> it1 = check(it1) # non-empty iterator, returns a copy of the
original one
>>> it1.next()
1

In general you can use the idiom

it = check(it) # check for emptiness
if it:
  # do something

This time I have checked the examples here with my doctester
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410052 ;)

              Michele Simionato




More information about the Python-list mailing list