Generator Basics
What are Generators?
Generators are a powerful feature in Python that allow you to create iterators in a simple and memory-efficient way. Unlike traditional functions that return a complete list of values, generators produce values on-the-fly, one at a time, using the yield
keyword.
Basic Generator Syntax
Here's a simple example of a generator function:
def simple_generator():
yield 1
yield 2
yield 3
## Using the generator
gen = simple_generator()
for value in gen:
print(value)
Key Characteristics of Generators
Characteristic |
Description |
Lazy Evaluation |
Values are generated only when requested |
Memory Efficiency |
Generates items one at a time, saving memory |
Iteration Support |
Can be used in for loops and with iteration methods |
Creating Generators
Generators can be created in two primary ways:
1. Generator Functions
def countdown(n):
while n > 0:
yield n
n -= 1
## Using the generator function
for number in countdown(5):
print(number)
2. Generator Expressions
## Generator expression
squared_gen = (x**2 for x in range(5))
for square in squared_gen:
print(square)
Flow of Generator Execution
graph TD
A[Start Generator] --> B{First yield}
B --> C[Pause Execution]
C --> D[Resume on Next Request]
D --> E{Next yield}
E --> F[Pause Again]
Advanced Generator Concepts
Generator State Preservation
Generators maintain their internal state between calls, allowing for complex iteration logic:
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
## Generate first 5 Fibonacci numbers
fib_gen = fibonacci()
for _ in range(5):
print(next(fib_gen))
Why Use Generators?
- Memory Efficiency
- Simplified Iteration Logic
- Handling Large Data Streams
- Lazy Computation
At LabEx, we recommend generators as an essential tool for efficient Python programming, especially when dealing with large datasets or complex iteration scenarios.