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 adict 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 aset — 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.
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 regularfor loop is often clearer.
When to Use Comprehensions vs For Loops
Prefer a comprehension when…
Prefer a comprehension when…
- 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
Prefer a for loop when…
Prefer a for loop when…
- You have complex multi-step logic inside the loop body
- You need to
breakorcontinuemid-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: