Approx. read time: 4.1 min.

Post: Learn about Python Generators

Lesson: Understanding Python Generators

Introduction

Generators in Python are a powerful tool for creating iterators in a more efficient and readable way. They are similar to functions but instead of returning a single value, they yield multiple values one at a time, pausing execution between each yield. This lesson will help you understand how to create and use generators effectively.

Key Concepts

  • Generators vs. Iterators:
    • Iterators: Objects that allow you to iterate over a sequence of values.
    • Generators: Special types of iterators that are defined using a function and the yield keyword.
  • Yield Statement: The yield statement is used in a function to make it a generator. It pauses the function and returns a value to the caller, resuming from the same point when the next value is requested.
  • Memory Efficiency: Generators are memory efficient because they generate values on the fly and do not store the entire sequence in memory.

How Generators Work

When you call a generator function, it returns a generator object without executing the function. When you iterate over this generator object, the function executes until it hits a yield statement. The value after yield is returned to the caller, and the function’s state is saved for subsequent calls.

Example of a Generator

Here’s a simple example of a generator function that generates random lottery numbers:

import random

def lottery():
    # Returns 6 numbers between 1 and 40
    for i in range(6):
        yield random.randint(1, 40)
    
    # Returns a 7th number between 1 and 15
    yield random.randint(1, 15)

for random_number in lottery():
    print("And the next number is... %d!" % random_number)

How This Example Works

  1. Defining the Generator: The lottery function is defined as a generator using the yield keyword.
  2. Returning an Iterator: When lottery is called, it returns a generator object.
  3. Generating Values: On each iteration, the generator produces the next random number, pausing execution and resuming for the next value.
  4. Iteration: The for loop iterates over the generator, printing each number as it is yielded.

Detailed Example: Fibonacci Series Generator

Let’s create a generator function that generates the Fibonacci series. The Fibonacci series starts with two ones, and each subsequent number is the sum of the previous two.

Explanation

The Fibonacci series follows this pattern:

  • F(0) = 1
  • F(1) = 1
  • F(n) = F(n-1) + F(n-2) for n ≥ 2

Writing the Fibonacci Generator

def fib():
    a, b = 1, 1
    while True:
        yield a
        a, b = b, a + b

Testing the Fibonacci Generator

import types

# Check if fib() returns a generator
if type(fib()) == types.GeneratorType:
    print("Good, The fib function is a generator.")

# Print the first 10 Fibonacci numbers
counter = 0
for n in fib():
    print(n)
    counter += 1
    if counter == 10:
        break

Explanation of the Fibonacci Generator

  1. Initialization: The variables a and b are initialized to 1.
  2. Infinite Loop: The while True loop ensures that the generator continues indefinitely.
  3. Yielding Values: The yield statement returns the current value of a and pauses the generator.
  4. Updating Values: The line a, b = b, a + b updates a and b to the next values in the Fibonacci sequence.
  5. Testing: The test code checks if fib is a generator and prints the first 10 numbers of the Fibonacci series.

Assignment

  1. Task: Write a generator function that yields the Fibonacci series.
  2. Objective: Test your generator to print the first 10 numbers in the series.

Assignment Template

def fib():
    a, b = 1, 1
    while True:
        yield a
        a, b = b, a + b

# Testing code
import types

# Check if fib() returns a generator
if type(fib()) == types.GeneratorType:
    print("Good, The fib function is a generator.")

# Print the first 10 Fibonacci numbers
counter = 0
for n in fib():
    print(n)
    counter += 1
    if counter == 10:
        break

Assignment Answer Key

Here is the complete solution to the assignment:

def fib():
    a, b = 1, 1
    while True:
        yield a
        a, b = b, a + b

# Testing code
import types

# Check if fib() returns a generator
if type(fib()) == types.GeneratorType:
    print("Good, The fib function is a generator.")

# Print the first 10 Fibonacci numbers
counter = 0
for n in fib():
    print(n)
    counter += 1
    if counter == 10:
        break

Conclusion

Generators in Python offer a powerful way to handle large sequences of data without consuming much memory. They are easy to create using the yield statement and provide an efficient way to iterate over large datasets or infinite sequences. By practicing with examples like the lottery numbers generator and the Fibonacci series generator, you can become proficient in using generators in your Python programs.

Additional Practice

  • Prime Number Generator: Write a generator function that yields prime numbers.
  • Countdown Timer: Write a generator function that counts down from a given number to zero.

You can use the Trinket.io Python compiler to test your code online.

About the Author: Bernard Aybout (Virii8)

I am a dedicated technology enthusiast with over 45 years of life experience, passionate about computers, AI, emerging technologies, and their real-world impact. As the founder of my personal blog, MiltonMarketing.com, I explore how AI, health tech, engineering, finance, and other advanced fields leverage innovation—not as a replacement for human expertise, but as a tool to enhance it. My focus is on bridging the gap between cutting-edge technology and practical applications, ensuring ethical, responsible, and transformative use across industries. MiltonMarketing.com is more than just a tech blog—it's a growing platform for expert insights. We welcome qualified writers and industry professionals from IT, AI, healthcare, engineering, HVAC, automotive, finance, and beyond to contribute their knowledge. If you have expertise to share in how AI and technology shape industries while complementing human skills, join us in driving meaningful conversations about the future of innovation. 🚀