How do list comprehensions work in Python?

A concise one-line syntax for building a new list by transforming or filtering another iterable replaces most simple for-loop patterns.

Python

Overview

A list comprehension is a compact way to create a list from an existing iterable. The general form is `[expression for item in iterable if condition]`. They are faster than equivalent `for` loops and considered idiomatic Python.

Key Points

  • •Basic form: `[expr for x in iterable]` applies `expr` to every item.
  • •With filter: `[expr for x in iterable if condition]` skips items where condition is false.
  • •Nested: `[expr for x in outer for y in inner]` equivalent to nested for loops.
  • •Dict and set comprehensions work the same way: `{k: v for …}` and `{expr for …}`.
  • •Generator expressions use `()` instead of `[]` and are lazy (memory-efficient for large sequences).

Examples

Transform a list

python
# Old way
squares = []
for n in range(10):
    squares.append(n ** 2)

# Comprehension
squares = [n ** 2 for n in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Filter with a condition

python
evens = [n for n in range(20) if n % 2 == 0]
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

active_users = [u for u in users if u.is_active]

Dict comprehension

python
words = ['apple', 'banana', 'cherry']
lengths = {word: len(word) for word in words}
# {'apple': 5, 'banana': 6, 'cherry': 6}

Generator expression (lazy, memory-efficient)

python
# Doesn't build the list in memory computes on demand
total = sum(n ** 2 for n in range(1_000_000))

Pro Tip

Keep comprehensions readable one line is fine, but if you need more than one condition or a complex expression, a regular `for` loop is clearer. Comprehensions are not always faster; profile before optimising.