In Python, yield is a keyword used inside a function to turn it into a generator. Generators allow you to iterate over a sequence of values lazily (one at a time, on-demand), which can be far more memory-efficient than building a complete list all at once.
How it works
- When Python sees a
yield statement in your function, it doesn’t run the function body immediately.
- Instead, calling that function returns a generator object.
- Each time you call
next() on that generator (or loop over it), the function runs until it hits a yield, returns the yielded value, and pauses—remembering its state (local variables, instruction pointer, etc.).
- A subsequent
next() resumes right after the yield.
Simple example
def count_up_to(n):
i = 1
while i <= n:
yield i
i += 1
# Using the generator
for num in count_up_to(5):
print(num)
Output:
1
2
3
4
5
Here, count_up_to doesn’t create a list of [1,2,3,4,5] in memory; it yields one number at a time.
return vs yield
| Aspect | return | yield |
|---|
| Function type | Normal function | Generator function |
| What it returns | A value (and then exit) | A generator object (no exit) |
| Memory use | Eager (all at once) | Lazy (one at a time) |
| State retention | None | Keeps local state between yields |
| Iteration | Not directly iterable | Iterable by design (supports for) |
Practical uses
- Large data streams: Reading huge log files line by line
- Infinite sequences: e.g.
itertools.count()
- Pipelines: Chain multiple generators together with
yield from
Chaining with yield from
def gen_a():
yield from [1, 2, 3]
def gen_b():
yield from gen_a()
yield from ["a", "b"]
print(list(gen_b())) # [1, 2, 3, 'a', 'b']
When to use yield
- You don’t need all items at once.
- You want to start producing results immediately (and possibly stop early).
- You’re dealing with streams or very large datasets.
Any other questions about generators, or shall we dive into more advanced patterns (like sending values into a generator)? 😊