With lists, it is common to test whether the list is empty and perform special code for the empty case. With iterators, this becomes awkward -- testing whether the iterator is empty will use up the first item! The solution is an idiom based on itertools.tee().
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
# First, as a demo, we'll demonstrate the idiom with a list: # Code here that creates a list 'my_list' if not my_list: # Code here for the case where the list is empty else: # Code here for the case where the list is NOT empty # Now, we'll demonstrate how to do the same thing for iterators: # (note that this must be an ITERATOR, not an ITERABLE. So # it won't work correctly if 'my_iter' is of type list, but # works fine if we use 'my_iter = iter(list)'. For more on the # distinction between iterators and iterables, see the docs. import itertools # code here that creates an iterator 'my_iter' try: first = my_iter.next() except StopIteration: # Code here for the case where the iterator is empty else: my_iter = itertools.chain([first], my_iter) # Code here for the case where the iterator is NOT empty
It is slightly awkward to encapsulate this in a helper function ('is_empty'), but writing out the idiom directly is straightforward enough for any reader who knows what itertools.chain() does and knows that StopIteration is used to signal the end of an iterator.
Obviously, you may not need both branches. For example, if you need to do special processing when the iterator is empty, but then proceed with the normal handling, then the 'else' clause would be empty (just leave it out) and normal handling would be placed after the try-except statement.
Thanks and credit are due to Brian Roberts and Michele Simionato whose postings to c.l.py inspired me to post this recipe, and Fredrik Lundh who provided a better implementation.