generator expression
In Python, a generator expression is a concise expression that lets you construct a generator iterator without the need for a function.
Generator expressions are similar to list comprehensions, but instead of creating a list and holding the entire data in memory, it returns a generator iterator that produces items on demand. They’re useful when you’re dealing with large datasets or potentially infinite data streams.
Syntax
To create a generator expression, you use a syntax similar to a list comprehension, but instead of square brackets []
, you use parentheses ()
to enclose the expression:
(expression for item in iterable if condition)
Example
Suppose you want to generate squares of numbers in a given range:
>>> squares = (x**2 for x in range(5))
>>> squares
<generator object <genexpr> at 0x102e3acf0>
>>> for square in squares:
... print(square)
...
0
1
4
9
16
In this example, the generator expression on the first line creates a generator that calculates the square of each number in the specified range. In every iteration, the generator computes a new value and yields it on demand.
Related Resources
Tutorial
How to Use Generators and yield in Python
In this step-by-step tutorial, you'll learn about generators and yielding in Python. You'll create generator functions and generator expressions using multiple Python yield statements. You'll also learn how to build data pipelines that take advantage of these Pythonic tools.
For additional information on related topics, take a look at the following resources:
- Iterators and Iterables in Python: Run Efficient Iterations (Tutorial)
- Asynchronous Iterators and Iterables in Python (Tutorial)
- Python Generators 101 (Course)
- How to Use Generators and yield in Python (Quiz)
- Efficient Iterations With Python Iterators and Iterables (Course)
- Iterators and Iterables in Python: Run Efficient Iterations (Quiz)
- Asynchronous Iterators and Iterables in Python (Quiz)