SimpleTuts.com

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:

Both generator functions and expressions are powerful tools in Python for handling large datasets and implementing efficient iteration patterns.