Python 3 - Generator

Updated: 2018-06-29
  • returns a list: [x for x in range(3)]
  • returns a generator: (x for x in range(3))

List comprehensions can cause problems for large inputs by using too much memory.

Generator expressions don’t materialize the whole output sequence when they’re run. Instead, generator expressions evaluate to an iterator that yields one item at a time from the expression.

next() will return the next value, until it is exhausted:

>>> a = (x for x in range(3))
>>> next(a)
0
>>> next(a)
1
>>> next(a)
2
>>> next(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

Generator is composable

>>> a = (x for x in range(3))
>>> b = (y for y in a)
>>> next(b)
0
>>> next(b)
1

A recursive generator that generates Tree leaves in in-order.

def inorder(t):
    if t:
        for x in inorder(t.left):
            yield x

        yield t.label

        for x in inorder(t.right):
            yield x