Python

Python Generator Expressions

A generator expression is a concise way to create a generator, which produces values one at a time instead of creating and storing all values in memory at once.

Generator expressions are especially useful when working with large amounts of data.

Basic Syntax

(expression for item in iterable)

Notice the round parentheses ().

Compare:

[x for x in numbers]       # List comprehension
{x for x in numbers}       # Set comprehension
{x: x for x in numbers}    # Dictionary comprehension
(x for x in numbers)       # Generator expression

1. Basic Generator Expression

numbers = [1, 2, 3, 4, 5]

squares = (
    x ** 2
    for x in numbers
)

print(squares)

Output will look similar to:

<generator object <genexpr> at 0x...>

It does not immediately contain a list of results.

Instead, it contains a generator that can produce the values when needed.

2. Get Values Using next()

The next() function retrieves the next value from a generator.

numbers = [1, 2, 3, 4, 5]

squares = (
    x ** 2
    for x in numbers
)

print(next(squares))
print(next(squares))
print(next(squares))

Output:

1
4
9

Each call to next() produces the next value.

3. Generator Expression with for Loop

Usually, generators are consumed using a for loop.

numbers = [1, 2, 3, 4, 5]

squares = (
    x ** 2
    for x in numbers
)

for square in squares:
    print(square)

Output:

1
4
9
16
25

4. Generator vs List Comprehension

List comprehension

numbers = [1, 2, 3, 4, 5]

squares = [
    x ** 2
    for x in numbers
]

print(squares)

Output:

[1, 4, 9, 16, 25]

The list stores all the results.

Generator expression

numbers = [1, 2, 3, 4, 5]

squares = (
    x ** 2
    for x in numbers
)

for square in squares:
    print(square)

The generator produces each value when needed.

5. Why Use Generator Expressions?

Consider a very large sequence:

numbers = range(10000000)

Creating a list of all transformed values could require significant memory:

squares = [
    x ** 2
    for x in numbers
]

A generator does not create all those results at once:

squares = (
    x ** 2
    for x in numbers
)

Values are generated one at a time.

This is called lazy evaluation.

6. Generator Expression with Condition

Like comprehensions, generator expressions can include conditions.

numbers = range(1, 11)

even_numbers = (
    x
    for x in numbers
    if x % 2 == 0
)

for number in even_numbers:
    print(number)

Output:

2
4
6
8
10

7. Generate Squares of Even Numbers

numbers = range(1, 11)

result = (
    x ** 2
    for x in numbers
    if x % 2 == 0
)

for value in result:
    print(value)

Output:

4
16
36
64
100

8. Generator Expression with Strings

names = ["Ram", "Sita", "Hari", "Gita"]

uppercase_names = (
    name.upper()
    for name in names
)

for name in uppercase_names:
    print(name)

Output:

RAM
SITA
HARI
GITA

9. Get String Lengths

names = ["Ram", "Sita", "Hari", "Rajendra"]

lengths = (
    len(name)
    for name in names
)

for length in lengths:
    print(length)

Output:

3
4
4
7

10. Generator Expression with sum()

Generator expressions work particularly well with functions such as sum().

numbers = range(1, 6)

total = sum(
    x ** 2
    for x in numbers
)

print(total)

Output:

55

The squares are generated as sum() needs them.

You don't need to create an intermediate list:

# Less memory efficient for large data total = sum([
    x ** 2
    for x in numbers
])

Instead:

total = sum(
    x ** 2
    for x in numbers
)

11. Generator Expression with max()

numbers = [10, 25, 30, 15, 40]

largest = max(
    x * 2
    for x in numbers
)

print(largest)

Output:

80

12. Generator Expression with min()

numbers = [10, 25, 30, 15, 40]

smallest = min(
    x * 2
    for x in numbers
)

print(smallest)

Output:

20

13. Generator Expression with any()

any() checks whether at least one generated value is True.

numbers = [1, 3, 5, 8, 9]

result = any(
    x % 2 == 0
    for x in numbers
)

print(result)

Output:

True

There is an even number (8).

14. Generator Expression with all()

all() checks whether every generated value is True.

numbers = [2, 4, 6, 8]

result = all(
    x % 2 == 0
    for x in numbers
)

print(result)

Output:

True

15. Generator Expression with any()

Checking whether any student passed:

marks = [25, 35, 45, 30]

result = any(
    mark >= 40
    for mark in marks
)

print(result)

Output:

True

At least one student has marks of 40 or above.

16. Generator Expression with all()

Checking whether all students passed:

marks = [55, 65, 75, 80]

result = all(
    mark >= 40
    for mark in marks
)

print(result)

Output:

True

17. Convert Generator to List

A generator can be converted into a list using list().

numbers = [1, 2, 3, 4, 5]

squares = (
    x ** 2
    for x in numbers
)

result = list(squares)

print(result)

Output:

[1, 4, 9, 16, 25]

After converting the generator to a list, the generator has been consumed.

18. Generator Can Be Consumed Only Once

Consider:

numbers = [1, 2, 3, 4, 5]

squares = (
    x ** 2
    for x in numbers
)

print(list(squares))
print(list(squares))

Output:

[1, 4, 9, 16, 25]
[]

Why is the second result empty?

Because the generator has already been consumed.

If you need to iterate over the values multiple times, a list may be more appropriate.

19. Generator with range()

Generators work very well with range().

numbers = (
    x
    for x in range(1, 6)
)

for number in numbers:
    print(number)

Output:

1
2
3
4
5

20. Large Data Example

Suppose we need to process numbers from 1 to 10 million.

numbers = range(1, 10000001)

squares = (
    x ** 2
    for x in numbers
)

for square in squares:
    if square > 100000000:
        print(square)
        break

The generator does not need to create ten million squared values beforehand.

It generates values as they are requested.

21. Practical Example : Employee Salaries

employees = {
    "Ram": 35000,
    "Sita": 55000,
    "Hari": 45000,
    "Gita": 70000
}

high_salaries = (
    salary
    for salary in employees.values()
    if salary >= 50000
)

for salary in high_salaries:
    print(salary)

Output:

55000
70000

22. Practical Example : Student Marks

marks = [75, 85, 35, 90, 45]

passed_marks = (
    mark
    for mark in marks
    if mark >= 40
)

for mark in passed_marks:
    print(mark)

Output:

75
85
90
45

23. Practical Example : Product Prices

products = {
    "Laptop": 80000,
    "Mouse": 1500,
    "Keyboard": 3000,
    "Monitor": 25000
}

expensive_products = (
    price
    for price in products.values()
    if price > 20000
)

for price in expensive_products:
    print(price)

Output:

80000
25000

24. Generator Expression with sum()

Calculate total product prices:

products = {
    "Laptop": 80000,
    "Mouse": 1500,
    "Keyboard": 3000,
    "Monitor": 25000
}

total = sum(
    price
    for price in products.values()
)

print(total)

Output:

109500

25. Generator Expression with Transformation

Calculate total price after a 10% discount:

products = {
    "Laptop": 80000,
    "Mouse": 1500,
    "Keyboard": 3000,
    "Monitor": 25000
}

total = sum(
    price * 0.9
    for price in products.values()
)

print(total)

Output:

98550.0

26. Generator Expression vs List Comprehension

FeatureList ComprehensionGenerator Expression
Syntax[]()
CreatesListGenerator
EvaluationImmediateLazy
MemoryMoreLess
ReusableYesNo, once consumed
Good forSmaller datasetsLarge datasets
Access by indexYesNo

Example:

numbers = [1, 2, 3, 4, 5]

# List squares_list = [x ** 2 for x in numbers]

# Generator squares_generator = (x ** 2 for x in numbers)

27. Generator Expression vs map()

Both can process values lazily.

Using map():

numbers = [1, 2, 3, 4, 5]

squares = map(
    lambda x: x ** 2,
    numbers
)

for square in squares:
    print(square)

Using a generator expression:

numbers = [1, 2, 3, 4, 5]

squares = (
    x ** 2
    for x in numbers
)

for square in squares:
    print(square)

For simple transformations, the generator expression can often be easier to read.

28. Generator Expression vs filter()

Using filter():

numbers = [1, 2, 3, 4, 5, 6]

even_numbers = filter(
    lambda x: x % 2 == 0,
    numbers
)

for number in even_numbers:
    print(number)

Using a generator expression:

numbers = [1, 2, 3, 4, 5, 6]

even_numbers = (
    x
    for x in numbers
    if x % 2 == 0
)

for number in even_numbers:
    print(number)

The generator expression combines filtering and transformation naturally.

29. When Should You Use a Generator Expression?

Use a generator expression when:

  • You are processing a large dataset.
  • You only need to iterate through values once.
  • You don't need random access.
  • You want to save memory.
  • You are passing the result to functions such as sum(), max(), min(), any(), or all().

For example:

total = sum(
    x ** 2
    for x in range(1000000)
)

This is a common and useful pattern.

Important Points to Remember

Basic syntax

(expression for item in iterable)

With condition

(expression for item in iterable if condition)

Main characteristic

A generator produces values one at a time.

List comprehension

[x ** 2 for x in numbers]

Creates all results immediately.

Generator expression

(x ** 2 for x in numbers)

Produces results when needed.

Remember

[] → List Comprehension
{} → Set Comprehension
{} → Dictionary Comprehension
() → Generator Expression
Interactive Sandbox
Python