PythonMastery

Generator expression vs list comprehension in Python

A list comprehension builds every value at once; a generator expression makes one value at a time. Compare their memory use, and see when to use each one.

A list comprehension uses square brackets and builds the whole list in memory. A generator expression uses round brackets and makes each value only when it is asked for.

The program

python
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(f"List: about {sys.getsizeof(squares_list) / 1_000_000:.0f} MB")
print(f"Generator: {sys.getsizeof(squares_gen)} bytes")

print(next(squares_gen))
print(next(squares_gen))
print(next(squares_gen))
example output · yours will differ
List: about 8 MB
Generator: 200 bytes
0
1
4

How it works

When to use each one

A generator can be used only once. After its values are used, it is empty:

python
gen = (x * x for x in range(5))

print(sum(gen))
print(sum(gen))
output
30
0

Learn the idea: Generators: Lazy Iteration with yield, Comprehensions: Lists, Dicts, Sets, Generators

A longer explanation: Use a generator when you only need one pass