stackademic

The leading education platform for anyone with an interest in software development.

Python List Comprehension

Concise syntax for building lists from iterables with optional filtering

Overview

List comprehensions let you create lists in a single readable expression. They replace many for loops plus append patterns and often run faster because the loop runs in optimized C code inside the interpreter.

Syntax / Usage

# Basic form: [expression for item in iterable]
squares = [x ** 2 for x in range(6)]
# [0, 1, 4, 9, 16, 25]

# With filter: [expression for item in iterable if condition]
evens = [n for n in range(10) if n % 2 == 0]
# [0, 2, 4, 6, 8]

# Nested loops
pairs = [(x, y) for x in range(3) for y in range(2)]
# [(0,0), (0,1), (1,0), (1,1), (2,0), (2,1)]

# With transformation
names = ["ada", "guido"]
capitalized = [n.title() for n in names]

Dictionary and set comprehensions use similar syntax: {k: v for ...} and {x for ...}.

Examples

Extract active user emails from a list of dicts:

users = [
    {"email": "a@x.com", "active": True},
    {"email": "b@x.com", "active": False},
]
active_emails = [u["email"] for u in users if u["active"]]

Flatten a matrix:

matrix = [[1, 2], [3, 4], [5, 6]]
flat = [cell for row in matrix for cell in row]
# [1, 2, 3, 4, 5, 6]

Common Mistakes

  • Building side effects inside comprehensions (prefer a plain loop for I/O)
  • Nesting too many levels—readability suffers past two loops
  • Using comprehensions when a generator expression would save memory on huge data
  • Forgetting that the if clause filters; if/else in the expression is for mapping

See Also

python-loops python-functions python-generators