← Back to Python, page 1

python-0004 · Medium mid

What are generators, and how do they differ from building a list?

A generator function uses yield to produce values one at a time, pausing between them, so it does not hold all values in memory. Calling it returns a generator object that is consumed by iteration. Lists store every element at once and can be indexed and reused, while a generator can be iterated only once.

Full answer
python
import sys

def countdown(n):
    while n > 0:
        yield n
        n -= 1

g = countdown(3)
print(type(g).__name__)
print(next(g))
print(list(g))
print(list(g))

squares_list = [i * i for i in range(1_000_000)]
squares_gen = (i * i for i in range(1_000_000))
print(sys.getsizeof(squares_list) > 1_000_000, sys.getsizeof(squares_gen) < 1_000)

Output:

text
generator
3
[2, 1]
[]
True True

countdown(3) returned a generator object without running the body. Each next() resumed the function until the next yield, and the loop consumed the rest. After exhaustion, a second loop produces nothing, which surprises people who expect list behaviour.

The memory comparison uses sys.getsizeof: the list of a million squares takes megabytes, while the generator object is a few hundred bytes regardless of length, because values are computed on demand.

Use generators for large or infinite sequences, streaming file lines, and pipelines ((line.strip() for line in f) feeding a filter). Use a list when you need the length, random access or several passes. yield from delegates to another iterable inside a generator.

python
import sys

def countdown(n):
    while n > 0:
        yield n
        n -= 1

g = countdown(3)
print(type(g).__name__)
print(next(g))
print(list(g))
print(list(g))

squares_list = [i * i for i in range(1_000_000)]
squares_gen = (i * i for i in range(1_000_000))
print(sys.getsizeof(squares_list) > 1_000_000, sys.getsizeof(squares_gen) < 1_000)

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • yield pauses and resumes the function
  • Generators compute values lazily
  • They can be iterated once
  • Lists allow indexing and repeat passes
  • Good for streams and pipelines

Common mistakes

  • Iterating a generator twice and expecting data the second time
  • Calling len() on a generator

Follow-ups

  • What does yield from do?
  • How would you write an infinite generator safely?

Tips

  • Show exhaustion