Thuta Learning
Python
AdvancedProgrammingBeginner

List Comprehensions

PythonLesson 4525 min

What you'll walk away with

  • Read [expression for item in iterable if condition] piece by piece and rewrite it as the equivalent for loop
  • Choose between list, set and dict comprehensions and generator expressions based on the result you need
  • Tell a trailing filter if apart from a leading a if c else b and use each correctly
  • Recognise when side effects or deep nesting mean a plain loop is clearer

Explain it simply

Explain it simply

If you hand someone a list and say "double every number and write the results on a new sheet" or "keep only the prices above 1000", one sentence is enough. A comprehension is the way to give Python that same one-sentence instruction.

You read [x * 2 for x in numbers] as "for every x in numbers, collect x * 2 into a list". The brackets decide the result: [ ] gives a list, { } gives a set or a dict. The original collection is left untouched; you always get a new one.

Problem → Why → Solution

The problem: append loops bury the intent

Say you need the names and emails of active users. With plain loops, every new collection costs the same four-line ritual: create an empty list, loop, test with if, append. In the code below the second loop forgot the active check, so inactive users will be emailed too.

users_loops.py
active_names = []
for user in users:
    if user["active"]:
        active_names.append(user["name"].title())

emails = []
for user in users:
    emails.append(user["email"].lower())  # bug: inactive users included

Why does this bug slip through so easily?

Each loop really says only two things, what to collect and what to skip, but a reader has to scan the whole body to find out. That is why a missing condition between two similar loops is easy to miss in review. A comprehension puts those two facts side by side in one expression, so the difference jumps out.

Core concept: the parts of a comprehension

A list comprehension has three parts: [expression for item in iterable if condition]. The for item in iterable part produces items one by one, and the optional if condition drops every item for which it is False. For each item that survives, the leading expression is evaluated and the result is added to a new list. The expression is written first, but it runs last: for, then if, then the expression.

It is exactly equivalent to a loop: result = []; for item in iterable: if condition: result.append(expression). Writing that loop out is the quickest way to decode a comprehension you do not understand. With two for clauses, the left one is the outer loop and the right one is the inner loop, the same order you would nest them in.

Written asProduces
[x * 2 for x in data]list: keeps order and duplicates
{x % 3 for x in data}set: duplicate results collapse
{k: v for k, v in pairs}dict: a repeated key keeps the last value
(x * 2 for x in data)generator: computes one item at a time, on demand

A generator expression never builds the whole list in memory: it hands out one item at a time when a consumer such as sum(), max() or any() asks for it. That makes it the right tool for aggregates over millions of rows. The catch is that it can be iterated only once; after that it is empty.

In Python 3 a comprehension's loop variable lives in its own scope, so it does not overwrite a variable with the same name outside. The expression runs once per item, so if you find yourself calling an expensive function both in the condition and in the expression, store the result with the walrus operator (:=) instead.

Mental model: a sieve and a machine
  1. Take the next item from the iterable
  2. Drop it if the if-clause is False
  3. Compute the expression for it
  4. Collect into a list, set or dict

The trailing if is a sieve that drops items; the leading expression is a machine that reshapes every item that passes.

General pattern

python
new_list = [expression for item in iterable if condition]
new_set = {expression for item in iterable if condition}
new_dict = {key_expr: value_expr for item in iterable if condition}
lazy_items = (expression for item in iterable if condition)

# two for clauses: the left one is the outer loop
pairs = [(a, b) for a in outer for b in inner]

The brackets decide the result type, and only the key_expr: value_expr form makes a dict. The if condition is always optional and always comes last. Round brackets give a generator, not a tuple.

Example: every kind of comprehension

This example walks through the comprehension forms one at a time, using range() and a short word list. Before running it, translate each line into its equivalent loop in your head and predict the output.

comprehensions.py
# List comprehension: transform every item
squares = [x**2 for x in range(10)]
print(f"Squares: {squares}")

# With a condition: keep only some items
evens = [x for x in range(20) if x % 2 == 0]
print(f"Evens: {evens}")

# Nested: one inner list per outer item
matrix = [[i * j for j in range(1, 4)] for i in range(1, 4)]
print(f"Matrix: {matrix}")

# Dictionary comprehension: key: value pairs
square_dict = {x: x**2 for x in range(1, 6)}
print(f"Dict: {square_dict}")

# Set comprehension: duplicate results collapse
unique_lengths = {len(word) for word in ["hello", "world", "python"]}
print(f"Lengths: {unique_lengths}")

# Generator expression: lazy, no list is built
total = sum(x**2 for x in range(10))
print(f"Sum of squares: {total}")

Code breakdown

  1. Transformsquares = [x**2 for x in range(10)]

    There is no if clause, so all ten items pass and each one is reshaped by x**2. The resulting list has ten elements.

  2. Filterevens = [x for x in range(20) if x % 2 == 0]

    The expression is just x, so nothing is reshaped; the comprehension only filters. Odd numbers fail x % 2 == 0 and are dropped.

  3. Nestedmatrix = [[i * j for j in range(1, 4)] for i in range(1, 4)]

    The outer comprehension's expression is itself a comprehension. Each i builds a fresh row list, so the result is a list of lists, a 3 x 3 multiplication table.

  4. Dictsquare_dict = {x: x**2 for x in range(1, 6)}

    The colon makes it a dict: x becomes the key and x**2 the value.

  5. Setunique_lengths = {len(word) for word in ["hello", "world", "python"]}

    "hello" and "world" both have length 5, so the set keeps a single 5. The result is {5, 6}.

  6. Generatortotal = sum(x**2 for x in range(10))

    As the only argument of a call, the generator needs no extra parentheses. sum() pulls the squares one at a time and reaches 285 without ever building a list.

You should see
Squares: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Evens: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
Matrix: [[1, 2, 3], [2, 4, 6], [3, 6, 9]]
Dict: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Lengths: {5, 6}
Sum of squares: 285

Filtering if versus choosing with if-else

if can appear in two places and the meaning is completely different. A trailing if is a filter: it removes items, so the result can get shorter, and it cannot have an else. A leading a if condition else b is part of the expression (a conditional expression): it keeps every item and picks one of two values, and the else is mandatory. The snippet also shows nested for clauses flattening a grid.

if_positions.py
nums = [3, -1, 4, -5]
positives = [n for n in nums if n > 0]              # filter: drops items
labels = ["pos" if n > 0 else "neg" for n in nums]  # choose: keeps every item
print(positives, labels)

grid = [[1, 2], [3, 4]]
flat = [cell for row in grid for cell in row]       # outer loop comes first
print(flat)

In real projects

Where this shows up in real projects

Comprehensions appear wherever data is reshaped: JSON records from an API, rows from a CSV file, results from a database query. Typical uses are a list of totals for paid orders, a set of customer names with duplicates removed, and a lookup table such as {order["id"]: order for order in orders} that turns repeated searches through a list into a single dict lookup, which is faster as well as clearer.

In data-heavy reports you will see generator expressions such as sum(row["amount"] for row in rows), which avoid copying millions of rows into a temporary list. any() and all() over a generator also stop as soon as the answer is known. In team code reviews, a comprehension that cannot be understood at a glance is usually sent back to be rewritten as a plain loop.

Common mistakes

Common mistakes

1. Using a comprehension for side effects

[print(name) for name in names] does print, but it also builds a throwaway list full of None. Comprehensions are for producing a new collection; for printing, writing files or updating a database, use a plain for loop.

2. Putting if-else at the end

[x for x in nums if x > 0 else 0] is a SyntaxError. To keep every item and choose a value, move the conditional expression to the front: [x if x > 0 else 0 for x in nums]. To drop items instead, use a filter if with no else at the end.

3. Iterating a generator twice

After squares = (x * x for x in nums), sum(squares) works but a following max(squares) raises ValueError: max() iterable argument is empty, because the generator is already exhausted. If you need the values more than once, store them with a list comprehension.

4. Duplicate keys in a dict comprehension

When the same key is produced twice, there is no error: the later value silently replaces the earlier one. To group several items under one key, use a loop with dict.setdefault() or collections.defaultdict(list).

Best practices

Best practices

  • Once you need more than two for clauses or two conditions, switch to a loop or a helper function.
  • When the result goes straight into sum(), any() or max(), use a generator expression instead of building a list.
  • Give the loop variable a meaningful name such as row or user, and save x for maths examples.

Mini challenge

Mini challenge: an order report

Produce a small report from a shop's order list using four different comprehensions. Do not use a plain loop with append.

  • paid_totals: a list of qty * price for every order whose status is "paid" and whose qty > 0
  • customers: a set of names that have at least one paid order
  • status_by_id: a dict mapping each order id to its status
  • revenue: the sum of qty * price over paid orders, computed with a generator, no list
order_report.py
orders = [
    {"id": 101, "customer": "Aye", "qty": 2, "price": 1500, "status": "paid"},
    {"id": 102, "customer": "Ko Ko", "qty": 1, "price": 9000, "status": "cancelled"},
    {"id": 103, "customer": "Aye", "qty": 3, "price": 2000, "status": "paid"},
    {"id": 104, "customer": "Mya", "qty": 0, "price": 4000, "status": "paid"},
]

# TODO: paid_totals = [... for o in orders if ...]
# TODO: customers = {... for o in orders if ...}
# TODO: status_by_id = {key: value for o in orders}
# TODO: revenue = sum(... for o in orders if ...)

# TODO: print the four results (sort the set so the output is stable)

Expected: The script prints: Paid totals: [3000, 6000] Customers: ['Aye', 'Mya'] Status by id: {101: 'paid', 102: 'cancelled', 103: 'paid', 104: 'paid'} Revenue: 9000

Show hint

Join two conditions with and. Wrapping the set in sorted() before printing keeps the output order stable. Order 104 has qty 0, so it adds nothing to revenue, yet Mya still counts as a paying customer.

Show solution
order_report.py
orders = [
    {"id": 101, "customer": "Aye", "qty": 2, "price": 1500, "status": "paid"},
    {"id": 102, "customer": "Ko Ko", "qty": 1, "price": 9000, "status": "cancelled"},
    {"id": 103, "customer": "Aye", "qty": 3, "price": 2000, "status": "paid"},
    {"id": 104, "customer": "Mya", "qty": 0, "price": 4000, "status": "paid"},
]

paid_totals = [o["qty"] * o["price"] for o in orders
               if o["status"] == "paid" and o["qty"] > 0]
customers = {o["customer"] for o in orders if o["status"] == "paid"}
status_by_id = {o["id"]: o["status"] for o in orders}
revenue = sum(o["qty"] * o["price"] for o in orders if o["status"] == "paid")

print("Paid totals:", paid_totals)
print("Customers:", sorted(customers))
print("Status by id:", status_by_id)
print("Revenue:", revenue)

Quick quiz 1 / 3

What does [n * 2 for n in range(5) if n % 2] evaluate to?

Quick quiz 2 / 3

Which line is a SyntaxError?

Quick quiz 3 / 3

What is {w[0]: w for w in ["apple", "avocado", "banana"]}?

What to remember

  • Read [expression for item in iterable if condition] as a loop that runs for, then if, then the expression.
  • [ ] gives a list, { } a set (or a dict with key: value), and ( ) a lazy generator you can iterate only once.
  • A trailing if drops items; a leading a if c else b picks a value for every item.
  • For side effects or deep nesting, a plain for loop is clearer.

Python Documentation — Functional Programming HOWTO — Python Software Foundation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

List Comprehensions | Thuta Learning