Generator Functions and Expressions in Python
Generator Functions
Generator functions in Python allow you to declare a function that behaves like an iterator. They use the yield statement to return values and suspend their execution state.
Example of a Generator Function:
def count_up_to(limit):
count = 1
while count <= limit:
yield count
count += 1
# Using the generator function
for num in count_up_to(5):
print(num)
Generator Expressions
Generator expressions provide a concise way to create generators on-the-fly. They are similar to list comprehensions but enclosed in parentheses ().
Example of a Generator Expression:
# Generator expression to generate squares of numbers from 1 to 5
square_gen = (x ** 2 for x in range(1, 6))
# Using the generator expression
for square in square_gen:
print(square)
Key Differences:
- Memory Usage: Generator functions and expressions are memory efficient as they generate values on-demand.
- Iteration: They can be iterated over only once; once exhausted, they need to be recreated.
- Syntax: Generator functions use
yieldstatements within a function definition, while generator expressions use parentheses.
Both generator functions and expressions are powerful tools in Python for handling large datasets and implementing efficient iteration patterns.