Generate values on demand with the yield keyword.
What You Will Learn
A function containing yield returns a generator object when called. Its body begins executing when the generator is advanced, preserving local state between yields until exhaustion.
Generators are useful for streams that need not materialize every item in memory.
Many iterator tools are lazy. Creating the iterator does not necessarily perform the work; advancing it can consume the original source.
Step-by-Step Example
The example below makes the behavior visible with small input values that you can change safely.
def countdown(starting_number):
remaining_number = starting_number
while remaining_number > 0:
yield remaining_number
remaining_number -= 1
print(list(countdown(4)))
How the Example Works
- The function countdown defines reusable behavior; its body executes when it is called, not when it is declared.
- The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.
For the chosen input, the expression list(countdown(4)) prints [4, 3, 2, 1]. Compare that result with the rule above before you change the argument.
Expected output from the example:
[4, 3, 2, 1]
When You Would Use This
This pattern is useful in readers for CSV files, event streams, or paginated API results, where collecting everything in memory is unnecessary. Because iterator state advances when values are consumed, decide whether you need a reusable collection or a one-time pass. Keep files and connections open until their lazy consumers finish.
Practice: Modify the Code
Write a generator that yields square numbers below a limit.
Verify the changed output against the behavior described above, including the relevant invalid or boundary case.
For complete parameters and version details, consult the official Python documentation.
Common Beginner Mistakes
- Expecting calling a generator function to immediately execute all its statements.
- Assuming yield behaves exactly like return and permanently ends the generator at the first value.
Key Takeaways
- Generate values on demand with the yield keyword.
- A function containing yield returns a generator object when called.
- Generators are useful for streams that need not materialize every item in memory.