Advertisement
Advanced Python, Memory Management & Garbage Collection

How can generators and iterators help reduce peak memory usage compared to building full lists?

Short answer

Generators produce values lazily, one at a time, without materializing the entire sequence in memory -- so processing a huge dataset with a generator pipeline can use constant memory (O(1)) instead of memory proportional to the dataset size (O(n)) that a list-based approach…

Save Python mock interview
Advertisement
AModel answer
Generators produce values lazily, one at a time, without materializing the entire sequence in memory -- so processing a huge dataset with a generator pipeline can use constant memory (O(1)) instead of memory proportional to the dataset size (O(n)) that a list-based approach would require.
# Memory-heavy: builds a full list of a million squares
squares = [x**2 for x in range(1_000_000)]

# Memory-efficient: generator computes one at a time
squares_gen = (x**2 for x in range(1_000_000))
total = sum(squares_gen)  # never holds all values at once
Real-world example
A CSV-processing script switches from reading all rows into a list to iterating with a generator expression, cutting peak memory usage from gigabytes to megabytes for very large files.
Likely follow-ups
  • When does a list still outperform a generator despite using more memory?
  • How does itertools.islice help limit generator consumption?
Related topics