🔹 Introduction
Python generators provide a powerful way to work with iterators and lazy evaluation. They allow you to create functions that yield values one at a time, instead of returning everything at once.
This can save memory and improve performance, especially when working with large datasets.
🎯 Objective
In this guide, you’ll learn how to:
- Create a generator using the yield keyword
- Use a generator in a for loop
- Understand how generators help with memory efficiency
💻 Example Code
def number_generator(n):
"""A simple generator that yields numbers from 1 to n."""
for i in range(1, n + 1):
yield i
# Using the generator
print("Generated numbers:")
for number in number_generator(5):
print(number)
📘 Explanation
Let’s break down the program:
- number_generator(n): A generator function that uses yield to produce numbers one at a time from 1 to
n
. - yield: Pauses the function and returns a value. On next call, continues from where it left off.
- for number in number_generator(5): Iterates through each yielded value until the generator is exhausted.
🚀 How to Run the Program
You can run this script in any Python 3 environment:
- Save the code in a file named
generator_example.py
- Open a terminal or command prompt
- Run the command:
python generator_example.py
- You should see the numbers 1 through 5 printed, one per line