Sub topic 13
Streaming Data with Generators
This chapter assumes you know Python loops and lists, Big O notation, and the difference between input space and auxiliary space. A generator lets you process data one item at a time, so memory use stays constant no matter how much data flows through.
The problem with building full lists
A list comprehension builds every result before you can use any of them. If you only need to sum, count, or scan the values, holding them all is wasted memory.
A generator is a function that uses yield instead of return. Each call to next() runs the function until the next yield, hands back one value, and pauses. The function's local variables stay alive between pauses, but nothing else is stored.
def squares_list(n):
return [i * i for i in range(n)]
def squares_gen(n):
for i in range(n):
yield i * i
print(sum(squares_gen(1000)))squares_list(n) holds all n values at once, so it uses O(n) auxiliary space. squares_gen(n) keeps only the loop counter and the current value. Summing it needs O(1) auxiliary space. Both run in O(n) time.
How a generator works
The consumer controls the pace. The generator never produces a value before it is requested. Because only one value exists at a time, peak memory does not grow with n.
Generator expressions
A generator expression looks like a list comprehension but uses parentheses.
n = 1_000_000
as_list = sum([i * i for i in range(n)]) # builds a list of n ints: O(n) space
as_gen = sum(i * i for i in range(n)) # one value at a time: O(1) space
print(as_list == as_gen)Both lines return the same number. Only the first allocates a million-element list.
Streaming a file
Generators fit large files. Iterating over a file object reads one line at a time, so you can chain generators into a pipeline.
def long_lines(path, limit):
with open(path) as f:
for line in f:
if len(line) > limit:
yield line.rstrip("\n")
def count_long_lines(path, limit):
count = 0
for _ in long_lines(path, limit):
count += 1
return countMemory use depends on the longest single line, not on the file size. Calling f.readlines() instead would load the whole file and cost O(n) space.
Limits and gotchas
- A generator can be consumed only once. After it is exhausted, iterating again gives nothing.
- A generator has no length and no indexing.
len(gen)andgen[3]raiseTypeError. - Wrapping a generator in
list(...)orsorted(...)collects every value and brings back O(n) space. - Algorithms that need random access or several passes over the data cannot stream without storing it.
Space-time view
Streaming usually does not change time complexity. It changes when the work happens and how much is held at once. If you need the same values twice, you either recompute them by creating a new generator, which costs extra time, or store them in a list, which costs space. This is the same trade-off covered earlier in the tutorial.
Exercise
A function reads a 50 GB log file with for line in f: and keeps a running count of lines that contain "ERROR". What is its auxiliary space, and what would change if it used f.readlines() first?
Show answer
With for line in f: the function holds one line and one counter at a time, so auxiliary space is O(1) with respect to file size (bounded by the longest line). With f.readlines() all lines are loaded into a list first, so auxiliary space becomes O(n) in the file size, which could exhaust memory on a 50 GB file.
Exercise
Why does max(i * i for i in range(n)) use O(1) space but sorted(i * i for i in range(n)) use O(n) space?
Show answer
max keeps only the largest value seen so far while consuming the generator one item at a time. sorted must collect all items into a list before ordering them, so it stores all n values.