Skip to content
BENIBIX Learn

Generator (Programming)

Development🧭 Programming ParadigmsAsynchronous Code

Also known as Generator Function, yield, Generators

A function that pauses at each yield and hands out one value at a time.

Think of it like

It is like a cook who makes one pancake each time you ask. No big stack waits on the side.

Example

Emma needs a million ticket numbers. A generator makes each one only when asked. So they never all sit in memory at once.

Why it matters

It saves memory, because values are made only when needed. It can even describe a list with no end.

Definition

A generator is a function that hands out values one at a time with the word yield. Each time it yields, it pauses and keeps its place. When the next value is asked for, it carries on from there. Python uses yield in a normal def. JavaScript marks a generator with function*. A generator is a quick way to make an iterator.

Example code

python
def count_to(n):
    i = 1
    while i <= n:
        yield i
        i += 1

print(list(count_to(3)))
# [1, 2, 3]
yield hands out one number, pauses, then goes on when asked again.
The generator yields 1, pauses, then yields 2 and 3 only when asked.

Common mistake

Thinking the body runs when you call a generator. The call only makes it. The code runs as you ask for each value.

Key takeaways

  1. 1
    yield. Hands out a value and pauses.
  2. 2
    Lazy. Makes each value only when asked.
  3. 3
    An easy iterator. Less code than writing one by hand.

Compare