List Comprehension
| Since: | Python 2(2000) |
|---|
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
sample_list_comprehension.py
# 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 = ["Kogami Shinya", "", "Tsunemori Akane", " ", "Ginoza Nobuchika"]
names = [name for name in raw_data if name.strip()]
print(names) # ['Kogami Shinya', 'Tsunemori Akane', 'Ginoza Nobuchika']
# 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.
enforcers = ["Kogami Shinya", "Ginoza Nobuchika"]
ranks = ["Enforcer", "Inspector", "Analyst"]
assignments = [(e, r) for e in enforcers for r in ranks]
print(assignments)
# [('Kogami Shinya', 'Enforcer'), ('Kogami Shinya', 'Inspector'), ('Kogami Shinya', 'Analyst'), ('Ginoza Nobuchika', 'Enforcer'), ('Ginoza Nobuchika', 'Inspector'), ('Ginoza Nobuchika', 'Analyst')]
# 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)
python3 list_comprehension.py
[1, 4, 9, 16, 25]
[4, 16, 36, 64, 100]
['HELLO', 'WORLD', 'PYTHON']
['odd', 'even', 'odd', 'even', 'odd', 'even']
['Kogami Shinya', 'Tsunemori Akane', 'Ginoza Nobuchika']
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[('Kogami Shinya', 'Enforcer'), ('Kogami Shinya', 'Inspector'), ('Kogami Shinya', 'Analyst'), ('Ginoza Nobuchika', 'Enforcer'), ('Ginoza Nobuchika', 'Inspector'), ('Ginoza Nobuchika', 'Analyst')]
{1: 'a', 2: 'b', 3: 'c'}
{1, 2, 3, 4}
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.