Generator Basics
What is a Generator?
A generator in Python is a special type of function that returns an iterator object, allowing you to generate a sequence of values over time, rather than computing them all at once and storing them in memory. Generators are defined using the yield
keyword, which pauses the function's execution and returns a value.
Basic Generator Syntax
def simple_generator():
yield 1
yield 2
yield 3
## Creating a generator object
gen = simple_generator()
## Iterating through generator values
for value in gen:
print(value)
Key Characteristics of Generators
Characteristic |
Description |
Memory Efficiency |
Generates values on-the-fly, reducing memory consumption |
Lazy Evaluation |
Values are produced only when requested |
Iteration |
Can be iterated over using for loops or next() function |
Generator Expression
Generators can also be created using generator expressions, which are similar to list comprehensions:
## Generator expression
squared_gen = (x**2 for x in range(5))
## Converting to list
squared_list = list(squared_gen)
print(squared_list) ## [0, 1, 4, 9, 16]
Generator Workflow
graph TD
A[Generator Function Called] --> B[Execution Starts]
B --> C{First yield Statement}
C --> |Pauses Execution| D[Returns Value]
D --> E[Waiting for next() or iteration]
E --> F{Next yield Statement}
F --> |Resumes Execution| G[Returns Next Value]
G --> H[Continues Until StopIteration]
Practical Example
def fibonacci_generator(n):
a, b = 0, 1
count = 0
while count < n:
yield a
a, b = b, a + b
count += 1
## Using the Fibonacci generator
for num in fibonacci_generator(6):
print(num)
When to Use Generators
- Processing large datasets
- Creating infinite sequences
- Implementing custom iterators
- Reducing memory overhead
By understanding generators, you can write more memory-efficient and elegant Python code. LabEx recommends practicing with different generator scenarios to master this powerful feature.