Skip to content

Module 10 · Comprehensions and Advanced Iteration — topic 6 of 13

Generator expressions

Comprehension syntax with parentheses that produces values lazily, saving memory; using generator expressions with sum, any, all, max and in pipelines, and their one-pass nature.

Beginner 10 min read·Lesson 150 of 306 in Python Programming

Learning objectives

  • Write generator expressions and pass them to functions
  • Explain memory and laziness benefits
  • Recognise that a generator can be consumed only once

Definition

A generator expression, written (expression for item in iterable), creates a generator that produces each value only when it is requested, instead of building the whole collection in memory.

Introduction

sum(x * x for x in range(1_000_000)) adds a million squares without ever creating a list of a million numbers. The parentheses make it a generator expression.

Why it matters

Generator expressions process large or endless data streams with constant memory, and with any() or all() they can stop early as soon as the answer is known.

Detailed explanation

Syntax: the same as a list comprehension but with parentheses. When it's the only argument to a function, the extra parentheses can be dropped: sum(x for x in data).

Evaluating a generator expression creates a generator object; no items are computed yet. Values are produced one at a time as something iterates over it.

Memory use is constant regardless of the number of items, because only the current item exists.

A generator can be iterated only once. After it is exhausted, iterating again yields nothing. Use a list if you need the data twice.

any() and all() short-circuit: any(x > 100 for x in data) stops at the first match.

Generators chain into pipelines: lines → stripped lines → non-empty lines → numbers, each stage lazy.

Syntax

Python
squares = (n * n for n in range(10)) # nothing computed yet
total = sum(n * n for n in range(10))
has_big = any(v > 100 for v in values)
longest = max(len(w) for w in words)
  • Parentheses make a generator.
  • Values are produced on demand.
  • Single use only.

Code examples

Lazy and memory-light

Python
import sys
as_list = [n * n for n in range(100_000)]
as_gen = (n * n for n in range(100_000))
print(sum(as_gen) == sum(as_list))
print(sys.getsizeof(as_gen) < 1000 < sys.getsizeof(as_list))
print(type(as_gen).__name__)
Output
True
True
generator

Single pass only

Python
evens = (n for n in range(10) if n % 2 == 0)
print(list(evens))
print(list(evens))
Output
[0, 2, 4, 6, 8]
[]

More examples

Pipelines and short-circuiting

Python
raw_lines = [" 42 ", "", "17", " ", "x", "8"]
stripped = (line.strip() for line in raw_lines)
non_empty = (s for s in stripped if s)
numbers = (int(s) for s in non_empty if s.isdigit())
print(sum(numbers))
checked = []
def is_big(v):
checked.append(v)
return v > 100
print(any(is_big(v) for v in [5, 300, 7, 900]))
print("checked:", checked)
Output
67
True
checked: [5, 300]

Step-by-step explanation

  • Each stage is a generator built on the previous one; nothing runs until sum() pulls values.
  • sum asks numbers for a value, which asks non_empty, which asks stripped — one line flows through the whole pipeline at a time.
  • 'x' is skipped by isdigit, so the total is 42 + 17 + 8.
  • any stops after 300, so 7 and 900 are never checked.

Expected output

Running “Pipelines and short-circuiting” prints exactly:

TextOutput
67
True
checked: [5, 300]

Practical applications

  • Processing huge log files line by line.
  • Streaming rows from a database or API.
  • Computing totals and checks without building intermediate lists.

Best practices

  • Use generator expressions inside sum, any, all, min and max.
  • Use lists when you need indexing, len() or several passes.
  • Build pipelines of small generator stages for large data.

Common mistakes

Reusing an exhausted generator

Avoid

data = (x for x in values)
print(max(data), min(data)) # min fails: empty

Prefer

data = list(values)
print(max(data), min(data))

A generator is consumed by the first pass.

Calling len() on a generator

Avoid

len(x for x in items)

Prefer

sum(1 for x in items) # or len(list(...))

Generators don't know their length in advance.

Important notes

  • Generator objects support next() and are iterators (see the next lessons).

Key takeaways

  • (expr for x in it) produces values lazily.
  • It uses constant memory and can be consumed once.
  • any() and all() stop early.

Try it yourself

  1. 1
    Count how many lines in a list of strings contain the word 'error' using a generator expression.
  2. 2
    Find the maximum word length in a paragraph without building a list.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
Practise this topic