A generator produces values one at a time, only when asked, instead of building a whole list in memory. This makes generators perfect for large files, data streams and infinite sequences.
What You Will Learn
- Write a generator with yield
- next() and StopIteration
- Generator expressions
- Memory savings vs lists
- Infinite generators and itertools
- Processing large files lazily
Prerequisites
Python Functions and Loops.
yield
def count_up(n):
i = 1
while i <= n:
yield i
i += 1
gen = count_up(3)
print(next(gen), next(gen), next(gen))
try:
next(gen)
except StopIteration:
print("StopIteration: generator finished")
print(list(count_up(5)))
1 2 3 StopIteration: generator finished [1, 2, 3, 4, 5]
Explanation: yield returns a value and pauses the function, keeping its local variables. The next call resumes after the yield. When the function ends, StopIteration is raised – a for loop handles this automatically.
Generator Expressions and Memory
import sys
squares_list = [x * x for x in range(1_000_000)]
squares_gen = (x * x for x in range(1_000_000))
print(sys.getsizeof(squares_list) > 1_000_000, sys.getsizeof(squares_gen) < 300)
print(sum(squares_gen))
True True 333332833333500000
Explanation: The list stores a million numbers (several MB); the generator object is only a couple of hundred bytes because it computes each value on demand. Use round brackets instead of square brackets to get a generator. A generator can be consumed only once.
Infinite Generators
from itertools import islice
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
print(list(islice(fibonacci(), 10)))
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Explanation: An infinite loop is fine in a generator because values are produced only when requested. islice takes the first 10.
Real Use: Filter a Large Log File
def errors(lines):
for line in lines:
if "ERROR" in line:
yield line.strip()
log = ["INFO start\n", "ERROR disk full\n", "INFO ok\n", "ERROR timeout\n"]
print(list(errors(log)))
# With a real file, nothing is loaded into memory at once:
# with open("server.log") as f:
# for e in errors(f):
# print(e)
['ERROR disk full', 'ERROR timeout']
Explanation: A file object is itself an iterator over lines, so chaining it with a generator processes gigabyte logs line by line. pandas uses the same idea with pd.read_csv(..., chunksize=10000), and Keras uses generators to feed training batches.
List vs Generator
| List | Generator | |
|---|---|---|
| Memory | Stores all items | One item at a time |
| Reuse | Many times | Once |
| Indexing / len() | Yes | No |
| Best for | Small data you reuse | Large or infinite streams |
Series
Python series: What is Python · Installation · Syntax · Variables · Operators · Decisions · Loops · Strings · Lists · Dictionary · Functions · Lambda · Modules · Files · Exceptions · OOP · Classes & Objects · Inheritance · Decorators · Generators · Virtual Environments
Interview Questions
Q: Difference between return and yield?
return ends the function; yield produces a value and pauses, resuming on the next request.
Q: What is a generator expression?
A compact generator written like a list comprehension but with parentheses.
Practice Exercises
- Write a generator that yields even numbers up to n.
- Write a generator that reads a CSV line by line and yields rows where amount > 1000.
Summary
Generators use yield to produce values lazily, saving memory and enabling infinite or streaming data; generator expressions offer a compact syntax.
Next: Virtual Environments
Machine Learning Tutorials, Courses and Certifications