Generators Basics
What are Generators?
Generators in Python are a powerful way to create iterators. Unlike traditional functions that return a complete result at once, generators can pause and resume their execution, yielding a series of values over time.
Key Characteristics of Generators
- Lazy Evaluation: Generators compute values on-the-fly, which saves memory and improves performance.
- Memory Efficiency: They generate values one at a time, instead of storing entire sequences in memory.
- State Preservation: Generators remember their state between calls.
Creating Generators
Generator Functions
def simple_generator():
yield 1
yield 2
yield 3
## Using the generator
gen = simple_generator()
for value in gen:
print(value)
Generator Expressions
## Generator expression
squared_gen = (x**2 for x in range(5))
print(list(squared_gen)) ## [0, 1, 4, 9, 16]
Generator Methods
Method |
Description |
next() |
Retrieves next value |
send() |
Sends a value into generator |
close() |
Terminates generator |
Advanced Generator Concepts
graph TD
A[Generator Creation] --> B[Yield Values]
B --> C[Pause Execution]
C --> D[Resume Execution]
D --> B
Example of Complex Generator
def fibonacci_generator(limit):
a, b = 0, 1
while a < limit:
yield a
a, b = b, a + b
## Using the generator
for num in fibonacci_generator(10):
print(num)
When to Use Generators
- Processing large datasets
- Creating infinite sequences
- Implementing custom iteration logic
- Reducing memory consumption
By understanding generators, you can write more efficient and elegant Python code. LabEx recommends practicing these concepts to master generator usage.