Lesson 31 of 55
PythonGenerators and Iterators
20 minutes
Course progress56%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 31 of 55
Python20 minutes
Keep these ideas in mind as you work through the lesson.
Generators produce items lazily using the yield keyword, turning a regular function into an iterator that emits values on demand.
def fib(limit):
a, b = 0, 1
while a < limit:
yield a
a, b = b, a + b
for n in fib(20):
print(n, end=' ')
# Output: 0 1 1 2 3 5 8 13
Generators are memory‑efficient for large data streams because they never store the whole sequence at once.