Python Essentials · 16 min · 140 XP

List comprehensions

Build lists and dictionaries in one readable line, and know when a loop reads better.

A list comprehension is a loop that builds a list, written in a single expression. Read it aloud: the square of n, for every n in numbers, if n is even.

python
numbers = [1, 2, 3, 4, 5, 6]
squares = [n * n for n in numbers if n % 2 == 0]
print(squares)  # [4, 16, 36]

# The loop it replaces:
squares = []
for n in numbers:
    if n % 2 == 0:
        squares.append(n * n)

The same shape builds a dictionary, {p["name"]: p["price"] for p in products}, or feeds a function directly without making a list: sum(p["price"] for p in products).

Use one when it reads more clearly than the loop, and not otherwise. A comprehension is for building a value. If the loop exists to do something (print, save, send), write a loop. If you need two ifs and a nested for to squeeze it into one line, a loop will be easier to read and to debug.

Loading your workspace…