Generator Expressions
Lesson 9 of 13 in Coddy's Python Iterators course.
Generator expressions are a concise way to create iterators in Python. They provide a more memory-efficient alternative to list comprehensions, especially when dealing with large datasets or infinite sequences.
Syntax of Generator Expressions
Generator expressions use a syntax similar to list comprehensions but with parentheses instead of square brackets:
(expression for item in iterable if condition)Key Features
- Lazy Evaluation: Generator expressions produce items one at a time and only when requested, saving memory.
- Single-Use Iterators: Once exhausted, they can't be reused without recreating the generator.
- Concise Syntax: They offer a compact way to define simple generator functions.
Example Usage
Here's a simple example of a generator expression that yields square numbers:
squares = (x**2 for x in range(5))
for square in squares:
print(square) # Outputs: 0, 1, 4, 9, 16
Comparison with List Comprehensions
While similar in syntax, generator expressions differ from list comprehensions in memory usage:
# List comprehension (creates a full list in memory)
squares_list = [x**2 for x in range(1000000)]
# Generator expression (creates a generator object)
squares_gen = (x**2 for x in range(1000000))
The generator expression is more memory-efficient as it doesn't create all values at once.
Use Cases
Generator expressions are particularly useful when:
- Working with large datasets
- Processing streams of data
- Creating data pipelines
By using generator expressions, you can create efficient, memory-friendly iterators for various data processing tasks in Python.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyCreate a generator expression that filters and transforms a sequence of numbers. The generator should produce the squares of even numbers from a given range.
You are provided with the following:
- Two integers as input:
startandend(inclusive)
Your task is to:
- Create a generator expression that:
- Iterates through the range from
starttoend(inclusive) - Filters out odd numbers
- Squares the remaining even numbers
- Iterates through the range from
- Use the generator expression in a loop to print each resulting value on a new line
The input will be provided as two space-separated integers representing start and end.
Try it yourself
# Read input
start, end = map(int, input().split())
# TODO: Create your generator expression here
generator_exp = None # Replace None with your generator expression
# Print the results
for value in generator_exp:
print(value)