Free lab Real Python 3. Zero installs. Your code stays in this browser. Open the playground

Generators & Lazy Iteration

16 min 40 XP
Study loop Read Predict Run Tweak Prove Review
Lesson 1 of 6 · View course roadmap
Step 1

Learn the idea

A generator is a function that produces values one at a time instead of building a whole list in memory. Swap return for yield and Python gives you a pausable function:

  • yield value — hands one value to the caller and freezes the function right there, local variables intact
  • next(gen) — resumes execution until the next yield
  • A for loop calls next() for you until the generator is exhausted

This is lazy evaluation: values are computed only when asked for. A generator over a 10 GB log file uses a few kilobytes of memory, because only one line exists at a time.

Generator expressions look like list comprehensions with round brackets: (n * n for n in range(10**9)) is created instantly — nothing is computed until you iterate.

Where you'll use this

Generators are how Python streams anything bigger than RAM: Django querysets, csv.reader, database cursors and every line-by-line log processor are lazy iterators. Data engineers chain generators into pipelines that crunch terabytes on a laptop.

Common mistakes

  • A generator is exhausted after one pass — looping over it a second time silently yields nothing. Recreate it or store the results if you need them twice.
  • Calling a generator function doesn't run any of its code: countdown(3) returns a generator object; the body only runs when you iterate.
  • Using len() on a generator → TypeError. A lazy stream has no length until it's consumed.

Pro tip

yield from delegates to another iterable in one line: def walk(tree): yield from tree.left; yield tree.value; yield from tree.right. It's the secret to elegant recursive generators.

Step 2

Try it yourself

Blank · autosaved

The lesson example is loaded and ready — press Run, then change something and run it again. Breaking it is part of learning. Want a clean slate? Tap “New blank”.

PYexample.py
+ Enter to run
Output appears here…
Step 3

Pass the challenge +40 XP

Blank · autosaved

Write a generator function countdown(n) that yields the numbers from n down to 1. Loop over countdown(3) printing each value on its own line, then print Liftoff!.

Target output
3
2
1
Liftoff!
PYchallenge.py
Run your code to check it…
Step 4

Check your understanding

1. What makes a function a generator?
2. Why can a generator represent an infinite sequence?
Last step

Your notes (saved on this device)

Tip: use and to move between lessons, K to search everything.

Your next ten minutes

Write Python that does something useful.

Start free. No install, no card, no passive video marathon.

Start learning free → Explore the path