Skip to content

List Comprehensions

List comprehensions provide a concise way to create lists by applying an expression to each item in an iterable, optionally filtering items. They’ve been in Python since version 2.0.

Required explicit loops to build lists:

# Traditional loop
squares = []
for x in range(10):
squares.append(x ** 2)
# Filtering
evens = []
for x in range(10):
if x % 2 == 0:
evens.append(x)

List comprehensions provide one-liner solutions:

# Basic comprehension
squares = [x ** 2 for x in range(10)]
# With filtering
evens = [x for x in range(10) if x % 2 == 0]
# Transform and filter
words = ["hello", "world", "python"]
upper_long = [w.upper() for w in words if len(w) > 5]
# Nested comprehensions
matrix = [[i * j for j in range(3)] for i in range(3)]
# [[0, 0, 0], [0, 1, 2], [0, 2, 4]]
# Multiple conditions
numbers = [x for x in range(50) if x % 2 == 0 if x % 3 == 0]
# Using multiple iterables
pairs = [(x, y) for x in range(3) for y in range(3)]
# Dictionary comprehension
squares_dict = {x: x ** 2 for x in range(5)}
# Set comprehension
unique_lengths = {len(word) for word in words}
  • Concise: One line instead of multiple
  • Readable: Clear intent (when not overused)
  • Faster: Often faster than equivalent loops
  • Pythonic: Idiomatic Python style
  • Functional: Encourages immutable patterns
  • Don’t sacrifice readability for conciseness
  • Can be slower for very complex expressions
  • Creates entire list in memory (use generators for large data)
  • Can become hard to read when nested or with multiple conditions
  • Alternative comprehensions: dict, set, generator
# Generator expression (lazy evaluation)
squares_gen = (x ** 2 for x in range(1000000))
# Flattening nested lists
nested = [[1, 2], [3, 4], [5, 6]]
flat = [item for sublist in nested for item in sublist]
# [1, 2, 3, 4, 5, 6]
# Conditional expressions
values = [x if x >= 0 else 0 for x in [-1, 2, -3, 4]]
# [0, 2, 0, 4]
# Too complex (BAD)
result = [
process(x, y, z)
for x in range(100)
if validate(x)
for y in get_ys(x)
if check(y)
for z in get_zs(y)
]
# Better: use regular loops for readability
  1. Create a list of squares for numbers 1 to 10

    Answer
    squares = [x ** 2 for x in range(1, 11)]
  2. Extract even numbers from [1, 2, 3, 4, 5, 6, 7, 8]

    Answer
    evens = [x for x in [1, 2, 3, 4, 5, 6, 7, 8] if x % 2 == 0]
  3. Convert ["apple", "banana", "cherry"] to uppercase

    Answer
    upper_fruits = [fruit.upper() for fruit in ["apple", "banana", "cherry"]]