5.13.1 Itertool functions

The following module functions all construct and return iterators. Some provide streams of infinite length, so they should only be accessed by functions or loops that truncate the stream.

chain( *iterables)
Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Used for treating consecutive sequences as a single sequence. Equivalent to:

     def chain(*iterables):
         for it in iterables:
             for element in it:
                 yield element

count( [n])
Make an iterator that returns consecutive integers starting with n. Does not currently support python long integers. Often used as an argument to imap() to generate consecutive data points. Also, used in izip() to add sequence numbers. Equivalent to:

     def count(n=0):
         while True:
             yield n
             n += 1

Note, count() does not check for overflow and will return negative numbers after exceeding sys.maxint. This behavior may change in the future.

cycle( iterable)
Make an iterator returning elements from the iterable and saving a copy of each. When the iterable is exhausted, return elements from the saved copy. Repeats indefinitely. Equivalent to:

     def cycle(iterable):
         saved = []
         for element in iterable:
             yield element
             saved.append(element)
         if len(saved) == 0:
             return
         while True:
             for element in saved:
                   yield element

Note, this is the only member of the toolkit that may require significant auxiliary storage (depending on the length of the iterable).

dropwhile( predicate, iterable)
Make an iterator that drops elements from the iterable as long as the predicate is true; afterwards, returns every element. Note, the iterator does not produce any output until the predicate is true, so it may have a lengthy start-up time. Equivalent to:

     def dropwhile(predicate, iterable):
         iterable = iter(iterable)
         while True:
             x = iterable.next()
             if predicate(x): continue # drop when predicate is true
             yield x
             break
         while True:
             yield iterable.next()

ifilter( predicate, iterable)
Make an iterator that filters elements from iterable returning only those for which the predicate is True. If predicate is None, return the items that are true. Equivalent to:

     def ifilter(predicate, iterable):
         if predicate is None:
             def predicate(x):
                 return x
         for x in iterable:
             if predicate(x):
                 yield x

ifilterfalse( predicate, iterable)
Make an iterator that filters elements from iterable returning only those for which the predicate is False. If predicate is None, return the items that are false. Equivalent to:

     def ifilterfalse(predicate, iterable):
         if predicate is None:
             def predicate(x):
                 return x
         for x in iterable:
             if not predicate(x):
                 yield x

imap( function, *iterables)
Make an iterator that computes the function using arguments from each of the iterables. If function is set to None, then imap() returns the arguments as a tuple. Like map() but stops when the shortest iterable is exhausted instead of filling in None for shorter iterables. The reason for the difference is that infinite iterator arguments are typically an error for map() (because the output is fully evaluated) but represent a common and useful way of supplying arguments to imap(). Equivalent to:

     def imap(function, *iterables):
         iterables = map(iter, iterables)
         while True:
             args = [i.next() for i in iterables]
             if function is None:
                 yield tuple(args)
             else:
                 yield function(*args)

islice( iterable, [start,] stop [, step])
Make an iterator that returns selected elements from the iterable. If start is non-zero, then elements from the iterable are skipped until start is reached. Afterward, elements are returned consecutively unless step is set higher than one which results in items being skipped. If stop is None, then iteration continues until the iterator is exhausted, if at all; otherwise, it stops at the specified position. Unlike regular slicing, islice() does not support negative values for start, stop, or step. Can be used to extract related fields from data where the internal structure has been flattened (for example, a multi-line report may list a name field on every third line). Equivalent to:

     def islice(iterable, *args):
         s = slice(*args)
         next = s.start or 0
         stop = s.stop
         step = s.step or 1
         for cnt, element in enumerate(iterable):
             if cnt < next:
                 continue
             if stop is not None and cnt >= stop:
                 break
             yield element
             next += step

izip( *iterables)
Make an iterator that aggregates elements from each of the iterables. Like zip() except that it returns an iterator instead of a list. Used for lock-step iteration over several iterables at a time. Equivalent to:

     def izip(*iterables):
         iterables = map(iter, iterables)
         while True:
             result = [i.next() for i in iterables]
             yield tuple(result)

repeat( object[, times])
Make an iterator that returns object over and over again. Runs indefinitely unless the times argument is specified. Used as argument to imap() for invariant parameters to the called function. Also used with izip() to create an invariant part of a tuple record. Equivalent to:

     def repeat(object, times=None):
         if times is None:
             while True:
                 yield object
         else:
             for i in xrange(times):
                 yield object

starmap( function, iterable)
Make an iterator that computes the function using arguments tuples obtained from the iterable. Used instead of imap() when argument parameters are already grouped in tuples from a single iterable (the data has been ``pre-zipped''). The difference between imap() and starmap() parallels the distinction between function(a,b) and function(*c). Equivalent to:

     def starmap(function, iterable):
         iterable = iter(iterable)
         while True:
             yield function(*iterable.next())

takewhile( predicate, iterable)
Make an iterator that returns elements from the iterable as long as the predicate is true. Equivalent to:

     def takewhile(predicate, iterable):
         iterable = iter(iterable)
         while True:
             x = iterable.next()
             if predicate(x):
                 yield x
             else:
                 break

See About this document... for information on suggesting changes.