Browse topics

List comprehensions

Version
3.14
Review
Draft

Summary#

A list comprehension builds a new list from an iterable. It can transform each item, filter items and combine several for clauses in one expression.

Syntax#

python
[expression for item in iterable if condition]
[a if condition else b for item in iterable]
[cell for row in rows for cell in row]

Example#

python
orders = [("A1", 40), ("A2", 5), ("A3", 75)]

large = [order_id for order_id, total in orders if total >= 40]
labels = ["big" if total >= 40 else "small" for _, total in orders]
grid = [[1, 2], [3, 4]]
flat = [cell for row in grid for cell in row]

print(large)
print(labels)
print(flat)

Expected output#

Text
['A1', 'A3']
['big', 'small', 'big']
[1, 2, 3, 4]

Common mistakes#

A trailing if only filters and does not accept else. To choose between two values, put the conditional expression a if condition else b before the first for. In nested comprehensions, write the for clauses in the same order as the equivalent nested loops.

Version applicability#

All three forms and the example work on all Python 3 releases. The loop variable stays local to the comprehension. Python 3.12 began inlining list, dictionary and set comprehensions, which keeps that isolation but removes their separate traceback frame and changes what locals() shows inside them.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0