Full answer
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:
generator
3
[2, 1]
[]
True Truecountdown(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.
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