Hiprup

What are list comprehensions and when should you use them?

A list comprehension is a concise Python expression that builds a new list by iterating over one or more iterables, optionally filtering items. It combines for and if clauses into a single bracketed expression and is typically faster and more readable than the equivalent for-loop-plus-append pattern.

General form:

[expr for item in iterable if condition]

Simple examples:

squares  = [x * x for x in range(10)]
evens    = [x for x in range(20) if x % 2 == 0]
upper    = [name.upper() for name in ["ada", "linus"]]
pairs    = [(x, y) for x in range(3) for y in range(3) if x != y]

Why comprehensions are preferred:

  • Expressiveness — one line communicates intent (“a new list of X for each Y”) more clearly than a loop scaffold.

  • Performance — the loop is pushed into the C implementation of the list type, avoiding repeated attribute lookups of append in Python-level code.

  • Scoping — the loop variable lives inside the comprehension’s own scope (Python 3), so it doesn’t leak into the surrounding namespace.

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

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

# Transform + filter
names = ['Alice', 'Bob', 'Charlie', 'Diana']
long_upper = [name.upper() for name in names if len(name) > 3]
# ['ALICE', 'CHARLIE', 'DIANA']

# Dictionary comprehension
word_lengths = {word: len(word) for word in names}
# {'Alice': 5, 'Bob': 3, 'Charlie': 7, 'Diana': 5}

# Set comprehension
unique_lengths = {len(word) for word in names}
# {3, 5, 7}

# Nested comprehension (flatten)
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [num for row in matrix for num in row]
# [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Generator expression (lazy, memory efficient)
sum_squares = sum(x**2 for x in range(1000000))  # No list in memory

# Conditional expression (ternary in comprehension)
labels = ['even' if x % 2 == 0 else 'odd' for x in range(5)]
# ['even', 'odd', 'even', 'odd', 'even']

List comprehension replaces a 3-line for loop with one line. The filter (if condition) goes after the for clause. Dict comprehension creates key-value pairs.

Set comprehension creates unique values. Nested comprehension reads left-to-right: outer for first, inner for second. Generator expression uses () instead of [] — processes lazily without storing the full list in memory.

Show all four types: list, dict, set, and generator expressions. The generator expression for memory efficiency (sum without creating a list) is an advanced point.

Know when NOT to use comprehensions: complex logic, side effects, more than 2 nested levels.

What are list comprehensions and when should you use them? | Hiprup