List Comprehension
List comprehensions are a Python-specific feature that provides a concise syntax for creating lists in a single line. You can combine a for clause with a conditional expression to transform or filter data.
Syntax
# Basic list comprehension.
[expression for variable in iterable]
# List comprehension with a condition (filtering with an if clause).
[expression for variable in iterable if condition]
# Conditional expression (ternary operator) to transform values.
[value_if_true if condition else value_if_false for variable in iterable]
# Nested list comprehension (for processing two-dimensional data).
[expression for var1 in iterable1 for var2 in iterable2]
# Dictionary comprehension and set comprehension use the same syntax.
{key: value for variable in iterable}
{expression for variable in iterable}
Syntax Patterns
| Pattern | Description |
|---|---|
| [expression for x in iterable] | Creates a list by applying an expression to each element of the iterable. Used as an alternative to map(). |
| [expression for x in iterable if condition] | Creates a list by applying an expression only to elements that satisfy the condition. Used as an alternative to filter(). |
| [A if condition else B for x in iterable] | Creates a list by switching the output value based on a condition. |
| [expression for x in it1 for y in it2] | Creates a list over the Cartesian product of two iterables (equivalent to nested loops). |
| {k: v for x in iterable} | Dictionary comprehension. Creates a dictionary from key-value pairs. |
Sample Code
# Basic list comprehension that builds a list of squares.
squares = [x ** 2 for x in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]
# The equivalent result written with a for loop.
squares2 = []
for x in range(1, 6):
squares2.append(x ** 2)
# List comprehension with a condition — squares of even numbers only.
even_squares = [x ** 2 for x in range(1, 11) if x % 2 == 0]
print(even_squares) # [4, 16, 36, 64, 100]
# Convert a list of strings to uppercase.
words = ["hello", "world", "python"]
upper_words = [w.upper() for w in words]
print(upper_words) # ['HELLO', 'WORLD', 'PYTHON']
# Use a conditional expression (ternary operator) to label even and odd numbers.
labels = ["even" if x % 2 == 0 else "odd" for x in range(1, 7)]
print(labels) # ['odd', 'even', 'odd', 'even', 'odd', 'even']
# Remove empty strings from a list of strings.
raw_data = ["Alice", "", "Bob", " ", "Carol"]
names = [name for name in raw_data if name.strip()]
print(names) # ['Alice', 'Bob', 'Carol']
# Flatten a 2D list into a 1D list using nested list comprehension.
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [x for row in matrix for x in row]
print(flat) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Create a Cartesian product (all combinations) of two lists.
colors = ["red", "blue"]
sizes = ["S", "M", "L"]
variants = [(c, s) for c in colors for s in sizes]
print(variants)
# [('red', 'S'), ('red', 'M'), ('red', 'L'), ('blue', 'S'), ('blue', 'M'), ('blue', 'L')]
# Dictionary comprehension that swaps keys and values.
original = {"a": 1, "b": 2, "c": 3}
inverted = {v: k for k, v in original.items()}
print(inverted) # {1: 'a', 2: 'b', 3: 'c'}
# Set comprehension that removes duplicates.
nums = [1, 2, 2, 3, 3, 3, 4]
unique = {x for x in nums}
print(unique) # {1, 2, 3, 4} (order is not guaranteed)
Notes
List comprehensions run faster than equivalent for loops because the Python interpreter optimizes them internally. They also eliminate the need to manage a loop counter separately, keeping the code concise.
However, cramming too much logic into a single line hurts readability. As a rule of thumb, if a comprehension is not immediately obvious at a glance, or if nesting goes three levels deep or more, rewriting it as a regular for loop will result in more maintainable code.
A related syntax is the generator expression, which uses parentheses () instead of brackets. For example, (x**2 for x in range(10)) produces a generator rather than a list, so it does not load all elements into memory at once. When processing large amounts of data, generator expressions are more memory-efficient. For other ways to transform and filter data, see also map() / filter().
If you find any errors or copyright issues, please contact us.