Generators in Python are a simple way to create iterators using functions and the yield keyword.
They allow you to generate values one at a time, instead of returning them all at once — making them memory-efficient and faster for large datasets.
| Feature | Description |
|---|---|
| Definition | A function that returns an iterator object which generates values on the fly. |
| Keyword Used | yield instead of return. |
| Memory Usage | Low — values are produced only when needed (lazy evaluation). |
| Execution State | Remembers its state between each yield call. |
| Use Case | Handling large data, streaming, infinite sequences, etc. |
🧩 Example 1: Basic Generator
def my_generator():
for i in range(3):
yield i
# Using the generator
gen = my_generator()
print(next(gen)) # First value
print(next(gen)) # Second value
print(next(gen)) # Third valueOutput:
0
1
2(If you call next(gen) again, it raises StopIteration.)
🧩 Example 2: Using Generators with Loops
def countdown(n):
while n > 0:
yield n
n -= 1
for num in countdown(5):
print(num)Output:
5
4
3
2
1🧩 Example 3: Generator Expression (Compact Syntax)
Generators can also be created using parentheses () instead of square brackets [].
squares = (x**2 for x in range(5))
print(next(squares))
print(next(squares))
print(list(squares)) # Convert remaining items to listOutput:
0
1
[4, 9, 16]🧩 Example 4: Infinite Generator
Generators can create infinite sequences because they produce values lazily.
def infinite_numbers():
n = 1
while True:
yield n
n += 1
gen = infinite_numbers()
for i in range(5):
print(next(gen))Output:
1
2
3
4
5In Summary:
- Generators are iterators built using functions and
yield. - They save memory by producing one value at a time instead of generating all at once.
- Ideal for streaming large data, pipelines, and infinite sequences.
yieldpauses the function, andnext()resumes it from where it left off.
