Bernard Aybouts - Blog - Miltonmarketing.com

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.

For privacy reasons YouTube needs your permission to be loaded. For more details, please see our Privacy Policy – Legal Disclaimer – Site Content Policy.

The Longevity Blueprint: AI-Powered Health Optimization

Current step:1AI-Human Medical Analyzer: Smarter, Personalized Health
2AI-Human Medical Analyzer: Smarter, Personalized Health

> SYS.HEALTH: AI-Human Medical Analyzer_

// Revolutionize Your Diagnostics

Experience the perfect blend of cutting-edge AI precision and expert human care. Our revolutionary analyzer turns your raw health data into personalized, actionable insights tailored just for you.

> INITIALIZING_BIOMETRIC_SCAN...

[+] DATA_INPUT

Securely upload complex health parameters, including lab bloodwork and comprehensive medical history.

[+] PROCESSING

Advanced algorithmic parsing combined with human-level oversight ensures hyper-accurate data interpretation.

[+] OUTPUT_MATRIX

Receive smarter, faster, and truly personalized care strategies to take immediate charge of your health journey.

A name/nickname is required to continue.

> TRANSLATION_MATRIX_ACTIVE...
[ LANG_EN ]
Knowledge Heals, Prevention Protects
[ LANG_HI ]
ज्ञान ठीक करता है, रोकथाम सुरक्षा करती है
[ LANG_ZH ]
知识治愈,预防保护
[ LANG_JA ]
知識は癒し、予防は守る
[ LANG_HE ]
הידע מרפא, המניעה מגנה
[ LANG_AR ]
المعرفة تُشفي، والوقاية تحمي
[ LANG_FR ]
La connaissance guérit, la prévention protège

> SYS.AUTH: Data Processing Consent_

[ AWAITING_AUTHORIZATION ] By providing consent, you allow us to process your uploaded data through our proprietary AI-Human analysis system.

  • [+] SECURE_REVIEW: This ensures your information is carefully reviewed using advanced AI technology and certified professional oversight to deliver personalized health insights.
  • [+] PRIVACY_LOCK: Your privacy is our strict priority. Your data will only be used for this specific diagnostic purpose.

> SYS.UPLOAD: Share Medical Records [OPTIONAL]_

[ USER_CONTROL_ACTIVE ] Uploading your medical records during registration is entirely optional. You can choose to bypass this step and provide data later if it suits your timeline.

You dictate the data flow: share as much or as little as you’re comfortable with, and let us guide you toward better health.

[+] FORMAT_SUPPORT

We accept all file formats, including photos, PDFs, text documents, and raw official medical data.

[+] DATA_YIELD

Increased inputs correlate with higher precision. The more info you share, the better we tailor your personalized insights.

> NEXT_STEPS: Post-Registration Protocol_

Once your registration is complete, a human specialist from our team will personally reach out to you within 3-10 business days. We will discuss your health journey and map out exactly how we can support you.

About the Author: Bernard Aybout (Virii8)

Avatar Of 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. 🚀