How to Use List Comprehensions in Python
Learn how to write concise and efficient list comprehensions in Python for transforming and filtering data.
List comprehensions provide a concise way to create lists in Python. They’re more readable and often faster than traditional loops.
Basic Syntax
# Traditional loop
squares = []
for x in range(10):
squares.append(x ** 2)
# List comprehension
squares = [x ** 2 for x in range(10)]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
With Conditionals
Filter elements while creating the list:
# Get only even numbers
evens = [x for x in range(20) if x % 2 == 0]
print(evens) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# Filter and transform
even_squares = [x ** 2 for x in range(10) if x % 2 == 0]
print(even_squares) # [0, 4, 16, 36, 64]
If-Else in List Comprehensions
Use conditional expressions (ternary operator):
# Label numbers as even or odd
labels = ["even" if x % 2 == 0 else "odd" for x in range(5)]
print(labels) # ['even', 'odd', 'even', 'odd', 'even']
# Replace negative numbers with zero
numbers = [-3, -1, 0, 2, 5]
positive = [x if x > 0 else 0 for x in numbers]
print(positive) # [0, 0, 0, 2, 5]
Nested List Comprehensions
Work with nested data structures:
# Flatten a 2D list
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [num for row in matrix for num in row]
print(flat) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Create a matrix
matrix = [[i * j for j in range(1, 4)] for i in range(1, 4)]
print(matrix) # [[1, 2, 3], [2, 4, 6], [3, 6, 9]]
Working with Strings
# Convert to uppercase
words = ["hello", "world", "python"]
upper = [word.upper() for word in words]
print(upper) # ['HELLO', 'WORLD', 'PYTHON']
# Extract first letters
first_letters = [word[0] for word in words]
print(first_letters) # ['h', 'w', 'p']
# Filter by length
long_words = [word for word in words if len(word) > 4]
print(long_words) # ['hello', 'world', 'python']
Dictionary and Set Comprehensions
Similar syntax for other data structures:
# Dictionary comprehension
squares_dict = {x: x ** 2 for x in range(5)}
print(squares_dict) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# Set comprehension (removes duplicates)
nums = [1, 2, 2, 3, 3, 3, 4]
unique_squares = {x ** 2 for x in nums}
print(unique_squares) # {1, 4, 9, 16}
Practical Examples
# Parse CSV-like data
data = "1,2,3,4,5"
numbers = [int(x) for x in data.split(",")]
print(numbers) # [1, 2, 3, 4, 5]
# Filter files by extension
files = ["doc.txt", "image.png", "data.csv", "script.py"]
python_files = [f for f in files if f.endswith(".py")]
print(python_files) # ['script.py']
# Extract values from dictionaries
users = [{"name": "Alice", "age": 25}, {"name": "Bob", "age": 30}]
names = [user["name"] for user in users]
print(names) # ['Alice', 'Bob']
Summary
- Use
[expression for item in iterable]for basic transformations - Add
if conditionto filter elements - Use
if-elsein the expression for conditional values - Nest comprehensions for multi-dimensional data
- Use
{}for dict/set comprehensions