How to Create Generator Functions with yield in Python
Create a memory-efficient generator function using yield to produce a Fibonacci sequence up to a limit.
Python code
14 linesdef fibonacci_sequence(limit):
"""Generate Fibonacci numbers up to a given limit."""
a, b = 0, 1
while a <= limit:
yield a
a, b = b, a + b
if __name__ == "__main__":
fib_gen = fibonacci_sequence(100)
for number in fib_gen:
print(number, end=" ")
print()
Output
0 1 1 2 3 5 8 13 21 34 55 89
How it works
The yield statement pauses the function, saving its state, and returns a value to the caller. On the next iteration, execution resumes after yield, continuing the loop. This avoids storing the entire sequence in memory, making it ideal for large or infinite ranges. The generator is exhausted after its loop completes, so it can only be iterated once unless re-created.
Common mistakes
- Forgetting that a generator can only be iterated once; reuse requires creating a new generator.
- Using `return` inside a generator stops iteration instead of yielding further values.
- Assuming `yield` returns a value immediately without pausing state.
Variations
- Use a generator expression for simple transformations, e.g., `(x*x for x in range(10))`.
- Use `itertools.islice` to take a limited number of items from an infinite generator.
Real-world use cases
- Streaming large log files line-by-line without loading the whole file into memory.
- Generating paginated API responses lazily to handle huge datasets efficiently.
- Producing infinite sequences like sensor readings for real-time monitoring dashboards.
Sponsored
More from Functions & basics
- Add Type Hints to Function Parameters and Return in Python easy
- Benchmark list append vs comprehension in Python easy
- Build a Context Manager in Python with contextlib.contextmanager easy
- Build a Progress Callback Function for Loops in Python easy
- Cache expensive function with lru_cache in Python easy
- Calculate Time Difference Across Time Zones in Python easy
Keep learning
Related tutorials and quizzes for this topic.