What are iterators

Contents
  • Infinity
  • Generators
  • Effects
  • Pipes

A Python iterator Python’s provides many handy utilities for working with iterators; the next lessons on itertools are dedicated to those functions and their Haskell equivalents. is a sort of sequence that, unlike a list, computes each subsequent value only as it is needed rather than producing the entire list all at once. For example, from a range, we can produce an iterator of numbers. Here we construct an iterator xs that will produce three values: We are using Python 3, in which the range function produces an iterator. (In Python 2, range produced a list, and xrange produced an iterator.)

>>> xs = iter(range(1, 4))

We can use the next function to demonstrate pulling values from the iterator one at a time. The first three times we apply the next function, xs will produce a value. The fourth time, it raises StopIteration to indicate that the iterator is exhausted.

>>> next(xs)
1

>>> next(xs)
2

>>> next(xs)
3

>>> next(xs)
StopIteration

Sign up for access to the full page, plus the complete archive and all the latest content.