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.

Easy Python 3.9+ Aug 9, 2026 Functions & basics 12 views 0 copies

Python code

14 lines
Python 3.9+
def 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

stdout
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

  1. Use a generator expression for simple transformations, e.g., `(x*x for x in range(10))`.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Functions & basics

Related tutorials and quizzes for this topic.