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:

Python Syntax
(expression for item in iterable if condition)

Example

Suppose you want to generate squares of numbers in a given range:

Python
>>> 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.

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.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated April 15, 2025 • Reviewed by Leodanis Pozo Ramos