Skip to main content
Comprehensions let you build and transform collections in a single, readable line instead of writing multi-line for loops. Once you’re comfortable with them, you’ll reach for comprehensions constantly — they’re one of the most practical tools in everyday Python.

List Comprehensions

A list comprehension creates a new list by applying an expression to every item in an iterable, optionally filtering with a condition. Syntax: [expression for item in iterable if condition]

Transforming a list of dictionaries

A common real-world use case is extracting or reshaping data from a list of records:

Dictionary Comprehensions

A dictionary comprehension builds a dict using the same pattern, but with {key: value ...} syntax. Syntax: {key_expr: value_expr for item in iterable if condition}

Set Comprehensions

Set comprehensions work like list comprehensions but produce a set — automatically deduplicated, unordered. Syntax: {expression for item in iterable if condition}

Generator Expressions

Generator expressions look like list comprehensions but use () instead of []. The crucial difference: they are lazy — they compute one value at a time, only when you ask for the next item. This makes them extremely memory-efficient for large datasets.
When you only need to iterate through results once (e.g., summing, searching, writing to a file), prefer a generator expression. When you need random access or to iterate multiple times, use a list comprehension.

Reading a large file lazily

Generator expressions shine when processing files line by line without loading everything into memory:

Nested Comprehensions

You can nest comprehensions to flatten or work with multi-dimensional data. Keep readability in mind — if nesting gets confusing, a regular for loop is often clearer.

When to Use Comprehensions vs For Loops

  • You are building a new collection from an existing one
  • The transformation or filter fits comfortably on one or two lines
  • You want expressive, declarative code
  • You have complex multi-step logic inside the loop body
  • You need to break or continue mid-iteration
  • You are performing side effects (printing, writing files, updating external state) rather than building a collection

Complete Example: Filtering and Transforming Product Data

Generator expressions used inside a function call like sum(...) or max(...) don’t need an extra pair of parentheses — the function’s parentheses serve double duty: