How to Use yield in Python: Simple Guide with Examples
In Python,
yield is used inside a function to make it a generator that produces values one at a time, pausing after each yield and resuming on the next call. This helps save memory and allows iteration over large or infinite sequences without creating them all at once.Syntax
The yield keyword is used inside a function to return a value and pause the function's execution. When the function is called again, it resumes right after the yield. This makes the function a generator.
- def function_name(): defines the generator function.
- yield value returns a value and pauses.
- The function returns a generator object when called.
python
def simple_generator(): yield 1 yield 2 yield 3
Example
This example shows a generator function that yields numbers from 1 to 3. Each time we loop over it, it produces the next number without storing all numbers at once.
python
def count_up_to_three(): yield 1 yield 2 yield 3 for number in count_up_to_three(): print(number)
Output
1
2
3
Common Pitfalls
One common mistake is expecting a generator function to return a list or all values at once. Instead, it returns a generator object that produces values on demand. Another mistake is forgetting to use yield and using return inside the generator, which stops the function immediately.
python
def wrong_generator(): return 1 # This stops the function immediately yield 2 def correct_generator(): yield 1 yield 2 print(list(correct_generator())) # Correct way to get all values # Output: # [1, 2]
Output
[1, 2]
Quick Reference
| Concept | Description |
|---|---|
| yield | Pauses function and returns a value, making it a generator |
| Generator function | A function with at least one yield statement |
| Generator object | Returned when calling a generator function; produces values on demand |
| Iteration | Use a for loop or next() to get values from a generator |
| Memory efficiency | Generators produce values one at a time, saving memory |
Key Takeaways
Use
yield inside a function to create a generator that produces values lazily.Generator functions return a generator object, not a list of values.
Each
yield pauses the function and resumes on the next call.Generators save memory by producing one value at a time instead of all at once.
Avoid using
return to send values inside generators; use yield instead.