Skip to main content
Albero Academy

Generators

Produce values lazily with yield — memory-efficient sequences.

Advanced Python10 min

A generator is the easy way to create an iterator: write a normal function but use yield instead of return. Each yield produces a value and pauses the function, resuming from that exact point on the next request. Values are computed lazily, one at a time.

yield pauses and resumes

a generator function
def squares(n):
for i in range(n):
yield i * i # produce a value, then freeze here
gen = squares(5)
next(gen) # 0 — runs until the first yield
next(gen) # 1 — resumes, runs to the next yield
for s in squares(5):
print(s) # 0 1 4 9 16 — the usual way to consume it

Why it matters: memory & infinity

A generator holds only the current value, so it handles huge or even infinite streams that would never fit in a list:

lazy = scalable
# Sum a billion squares without building a billion-item list
total = sum(x * x for x in range(1_000_000_000))
def naturals(): # an INFINITE generator
n = 1
while True:
yield n
n += 1
# Take just what you need — it never tries to build the whole thing

Generator expressions

Like a comprehension but with parentheses — lazy instead of building a list. Ideal as an argument to sum, any, max:

(expr for …)
squares = (n * n for n in range(1000)) # lazy — nothing computed yet
any(x > 100 for x in data) # stops at the first match

Key takeaways

  1. 01A generator function uses yield to produce values lazily, pausing between them.
  2. 02It holds only the current value in memory — great for huge or infinite streams.
  3. 03next() drives it manually; a for loop is the usual way to consume it.
  4. 04Generator expressions (expr for …) are the lazy cousin of comprehensions.
  5. 05Use generators for large/one-pass/unbounded data; lists for small, reusable, indexable data.

Finished this chapter?

Mark it complete to track your progress through Python.