Generator Expression vs List Comprehension in Python

A list comprehension [x for x in range(10)] builds the entire list in memory immediately; a generator expression (x for x in range(10)) produces values lazil...

Published November 21, 2026

A list comprehension builds the whole list in memory immediately; a generator expression produces values one at a time on demand. Use a generator when you only iterate once or the data is large.

The concept

[x*x for x in data] uses square brackets and returns a list. (x*x for x in data) uses round brackets and returns a lazy generator.

Generators use almost no memory and can stop early, but you cannot index them or reuse them after they are exhausted.

Memory use

sum([x for x in range(10**7)]) # builds 10 million items first
sum(x for x in range(10**7)) # computes one at a time

Practical examples

Same result, different cost

squares_list = [n * n for n in range(5)]   # [0, 1, 4, 9, 16]
squares_gen  = (n * n for n in range(5))   # <generator object>
list(squares_gen)

Short-circuiting

any(is_prime(n) for n in range(10**9))   # stops at the first True

One-shot only

g = (x for x in 'abc')
list(g)  # ['a','b','c']
list(g)  # []  exhausted

Reading a big file lazily

lines = (l.strip() for l in open('big.log'))
errors = (l for l in lines if 'ERROR' in l)

Common mistakes

  • Iterating a generator twice.
  • Using len() or indexing on a generator.
  • Using a list when a generator would avoid memory problems.

Key takeaways

  • [] builds all, () is lazy.
  • Generators save memory and can short-circuit.
  • Single use.

FAQ

Are generators slower?

Slightly per item, but they avoid allocating the whole list.

When use a list?

When you need indexing, multiple passes or the length.

More Python articles