Skip to content
dreamcode
dreamcode
Map
Generators
Lesson 50 of 77
+15 XP on finish
PYTHON ADVANCEDChapter 9 · Python Advanced

Generators and Yield

A generator function yields values one by one using the yield keyword. It pauses execution after each yield, saving memory.

Worked example

How it reads

  • yield count returns a value and pauses the function state
  • for number in ... calls next() implicitly to retrieve values
Cloud tip: Generators are perfect for looping over very large datasets or files that don't fit in memory.
main.py
PYTHON
real Python, runs in your browser
Console
Run your code to see its output here.
YOUR TURN

Write a generator count_to(n) that yields 1 up to n, and print list(count_to(4)): [1, 2, 3, 4].

Press Run to check your work.