List Comprehensions
Overview
List comprehensions are a defining feature of Pythonic code. They provide a concise, readable, and highly optimized syntax to create a new list by transforming or filtering an existing iterable. In standard loops, you must declare an empty list and call .append() repeatedly. List comprehensions accomplish this in a single line. Furthermore, because they are implemented directly in C under the hood, they execute significantly faster than equivalent standard for loops.
Syntax
nums = [1, 2, 3, 4, 5]
# The standard (slower) loop approach:
squares = []
for n in nums:
squares.append(n ** 2)
# The List Comprehension approach:
# Syntax: [expression for item in iterable if condition]
squares = [n ** 2 for n in nums]
# Comprehension with a filtering condition (Only even numbers)
even_squares = [n ** 2 for n in nums if n % 2 == 0]
# Nested comprehension (Flattening a 2D matrix)
matrix = [[1, 2], [3, 4]]
flat = [num for row in matrix for num in row] # [1, 2, 3, 4]Common Pitfalls
- Over-engineering. If a list comprehension becomes so complex that it spans multiple lines and contains complex nested loops, it destroys readability. Use a standard loop in these cases.
- Forgetting that list comprehensions eagerly evaluate. If you run
[x for x in range(10_000_000)], it will immediately generate and store 10 million items in RAM, likely crashing the system. Use a Generator instead.
Interview Questions
List comprehensions do not need to look up the list object and invoke the .append() method on every iteration. The memory allocation and appending logic are handled directly at the C-level.
Real-World Example
Extracting specific fields from a list of complex dictionaries (a very common API response pattern).
users = [
{"name": "Alice", "status": "active"},
{"name": "Bob", "status": "inactive"},
{"name": "Charlie", "status": "active"}
]
# Cleanly extract only the names of active users
active_names = [user["name"] for user in users if user["status"] == "active"]
print(active_names) # ['Alice', 'Charlie']Check Your Knowledge
Test your understanding of List Comprehensions with these quick questions.