Python · Generators & Iterators

What is yield?

Easyyieldgeneratorkeywords

Interview question

What does the yield keyword do in Python?

How to answer

The short answer

yield turns a function into a function. When the function hits yield value, it:

  1. 1Produces value to the caller,
  2. 2Pauses local state (variables, instruction pointer),
  3. 3Resumes from that point on the next next() / for iteration.

Unlike return, which exits once, a generator can yield many times.

Python
def read_lines(path):
    with open(path) as f:
        for line in f:
            yield line.rstrip("\n")

def pairwise(items):
    it = iter(items)
    prev = next(it)
    for cur in it:
        yield prev, cur
        prev = cur

print(list(pairwise([1, 2, 3, 4])))
# [(1, 2), (2, 3), (3, 4)]

# yield from delegates to another iterable/generator
def flatten(nested):
    for part in nested:
        yield from part

print(list(flatten([[1, 2], [3]])))  # [1, 2, 3]

`yield` vs `return` in one line: return hands back one final result; yield streams many intermediate results while keeping state alive.

Lock it in with a real drill

You remember an answer longer once you have used it. Try a hands-on problem on this concept.

Open related drill