Generators
Generators
In the last lesson, you learned about iterators.
Generators are a simple way to create iterators.
They are powerful, memory-friendly, and common in real Python projects.
What Is a Generator?
A generator is a function that returns values one at a time using yield.
Unlike return, it pauses after each value and continues later.
Why Generators Matter
Generators help you:
- work with large data
- save memory
- create lazy sequences
- stream values step by step
return vs yield
Using return
def numbers():
return [1, 2, 3]
print(numbers())
Output
[1, 2, 3]
This creates all values at once.
Using yield
def numbers():
yield 1
yield 2
yield 3
print(numbers())
Output
<generator object numbers at ...>
Get Values from Generator
Use a loop.
def numbers():
yield 1
yield 2
yield 3
for num in numbers():
print(num)
Output
1
2
3
Use next()
def colors():
yield "Red"
yield "Blue"
g = colors()
print(next(g))
print(next(g))
Output
Red
Blue
Generator with Loop
def count_up():
for n in range(1, 4):
yield n
for value in count_up():
print(value)
Output
1
2
3
Why Memory Efficient?
A generator creates one value when needed.
It does not store the full result list first.
Example: Large Range
for num in range(1_000_000):
pass
Generators are useful for large data like this.
Code Along
Create a generator named letters() that yields:
- A
- B
- C
Loop and print each letter.
Mini Challenge
Create a generator named even_numbers().
Tasks:
-
Yield:
- 2
- 4
- 6
Print all values.
Expected output:
2
4
6
Real World Use Case
Generators are used in file reading, APIs, streaming data, pipelines, and large reports.
Quiz
- What keyword creates generator values?
- What is the difference between
returnandyield? - Why are generators memory-friendly?
- Can generators be used in loops?
Assignment
Create a generator that yields three city names and print them in a loop.
Summary
You learned how generators use yield to return values one at a time efficiently.