Advanced Chapter 138 · 35 min read · Module 11: Advanced Python
yield Keyword
- After this chapter you can explain what yield does and how it differs from return.
- You can write a generator function and loop over it with for.
- You can use next() and understand StopIteration.
- You can use yield from to pass values from another iterable.
- You can send values into a generator with send() and know when generators save memory.
A normal function runs from start to end, gives back one answer with return, and then forgets everything. Sometimes you want something different: a function that hands out a value, pauses, and later continues from the same place. The yield keyword gives you exactly that.
A function that contains yield is called a generator function. When you call it, the body does not run yet. Python gives you a generator object, and each time you ask for the next value the function runs until the next yield, then freezes with all its local variables kept safe.
In this chapter you will learn how generators behave, how to read their values with for loops and next(), how yield from helps with nested work, and why generators are a good choice for large or endless streams of data.
From return to yield
When a function reaches return, it ends, and its local variables disappear. When a function reaches yield, it gives a value to the caller but only pauses. The next time a value is requested, the function wakes up on the line right after the yield and keeps going. Because of this, one function can produce many values over time without building a full list first.
def count_up(limit):
n = 1
while n <= limit:
yield n
n += 1
for number in count_up(3):
print(number)Calling count_up(3) does not print anything by itself. The for loop asks the generator for a value again and again. Each request runs the code until the next yield. When the function ends, the generator is finished and the loop stops by itself.
Using next() and StopIteration
You can control a generator by hand with the built-in next() function. Each call returns the next yielded value. When there are no more values, Python raises StopIteration. A for loop catches this signal quietly, which is why you normally never see it.
def letters():
print("start")
yield "a"
print("middle")
yield "b"
print("end")
g = letters()
print(next(g))
print(next(g))
try:
next(g)
except StopIteration:
print("done")Look at the order of the output. Nothing is printed when letters() is called. The text start appears only at the first next(). The generator pauses at each yield, so the print calls are spread over time. This lazy behaviour is the heart of generators.
Why generators save memory
A list stores every item at once. A generator stores only its current state and makes the next item when asked. If you need the sum of a million squares, you do not have to keep a million numbers in memory. You can also describe endless streams, such as all even numbers, because the generator never has to finish.
def squares(limit):
for n in range(1, limit + 1):
yield n * n
total = sum(squares(1000))
print(total)
evens = (n for n in range(10) if n % 2 == 0)
print(list(evens))The second part uses a generator expression, which looks like a list comprehension but uses round brackets. It also produces values lazily. Remember that a generator can be used only once. After it is exhausted, looping over it again gives nothing, so call the function again to get a fresh generator.
yield from
Sometimes a generator needs to pass along every value of another iterable. Writing a for loop with yield inside works, but yield from is shorter and clearer. It also connects the two generators properly, which matters for advanced features.
def chain(first, second):
yield from first
yield from second
print(list(chain([1, 2], "ab")))Sending values into a generator
A yield is an expression, so it can also receive a value. The caller uses send(value) and that value becomes the result of the paused yield. You must start the generator first with next() so it reaches its first yield. This pattern is used for coroutines and is less common than plain generators, but it shows that yield works in both directions.
def averager():
total = 0
count = 0
average = None
while True:
value = yield average
total += value
count += 1
average = total / count
g = averager()
next(g)
print(g.send(10))
print(g.send(20))
print(g.send(60))Reading a file lazily
Generators are perfect for reading large files line by line, filtering rows, or building chains of small steps. Each step takes one item, changes it, and passes it on. Because only one item is alive at a time, the program stays fast and small even for huge inputs.
Python syntax
def name(args):
...
yield valueyield from iterablegen = (expr for item in iterable if condition)Real-world applications
- Reading very large files line by line without loading them fully
- Producing endless sequences such as ids or Fibonacci numbers
- Building data pipelines where each step filters or transforms items
- Walking trees and folders with yield from
- Streaming rows from a database or an API page by page
Common mistakes
Fix: A generator is used up after one pass. Call the generator function again or store the values in a list if you need them twice.
Fix: The body runs only when you ask for values with for, next() or list(). Calling it just creates the generator object.
Fix: Use yield for every value you want to hand out. return stops the function and gives only one answer.
Fix: Call next(g) first so the generator reaches its first yield, or send None.
Important tips
- Use a generator when the result is large and you read it only once.
- Use list(gen) when you really need all values together.
- Prefer generator expressions for short one-line cases.
- Name generator functions with a verb or noun that describes the stream, such as read_lines.
Key points summary
- yield pauses a function and returns a value, keeping local state.
- A function with yield returns a generator object when called.
- next() asks for the next value; StopIteration means there are no more.
- Generators are lazy and use little memory.
- yield from passes through every value of another iterable.
- A generator can be consumed only once.
Exam and interview points
- A function containing yield is always a generator function, even if the yield is never reached.
- Generators raise StopIteration when exhausted.
- Generator expressions use parentheses, list comprehensions use square brackets.
- yield from simplifies delegating to a sub-generator.
- send() resumes the generator and sets the value of the yield expression.
Quick revision
- yield = pause and give a value
- Calling a generator function runs nothing yet
- next(g) gets one value
- for loops handle StopIteration for you
- Generators are single-use and memory friendly
- yield from forwards another iterable
Frequently asked questions
What is the difference between yield and return?
return ends the function and gives one value. yield gives a value and pauses, so the function can continue later and give more values.
Is a generator the same as an iterator?
Every generator is an iterator, so it works with for and next(). Generators are just a very easy way to write iterators.
Can a generator be restarted?
No. Once it is finished you must create a new generator by calling the function again.
When should I use a list instead?
Use a list when you need indexing, the length, or several passes over the data. Use a generator for one pass over a large or endless stream.
Practise this chapter
18 practice questions Take the chapter quiz