List comprehensions are one of Python's most powerful features for creating lists concisely and efficiently. This comprehensive guide covers everything you need to know.
Basic Syntax and Structure
The basic structure is: [expression for item in iterable]
# Traditional approach
squares = []
for x in range(10):
squares.append(x**2)
# List comprehension - more concise and faster
squares = [x**2 for x in range(10)]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# Transform strings
names = ['alice', 'bob', 'charlie']
capitalized = [name.capitalize() for name in names]
Filtering with Conditional Logic
# Simple filtering
evens = [x for x in range(20) if x % 2 == 0]
# Multiple conditions
filtered = [x for x in range(100) if x % 2 == 0 if x % 5 == 0]
# Conditional transformation
numbers = [x if x % 2 == 0 else -x for x in range(10)]
Nested List Comprehensions
# Create a 3x3 matrix
matrix = [[i*3+j for j in range(3)] for i in range(3)]
# Flatten a nested list
flattened = [num for row in matrix for num in row]
# Generate combinations
pairs = [(x, y) for x in [1, 2, 3] for y in ['a', 'b', 'c']]
Dictionary and Set Comprehensions
# Dictionary comprehension
squares_dict = {x: x**2 for x in range(5)}
# Invert dictionary
inverted = {v: k for k, v in squares_dict.items()}
# Set comprehension (removes duplicates)
unique_chars = {char for word in ['hello', 'world'] for char in word}
Performance Tips
List comprehensions are 30-40% faster than loops. For large datasets, use generator expressions:
# Generator expression (memory efficient)
large_squares = (x**2 for x in range(1000000))
print(next(large_squares)) # 0
Real-World Examples
# Process API data
users = [{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}]
adult_names = [user['name'] for user in users if user['age'] >= 18]
# Parse CSV
csv_lines = ['name,age', 'Alice,30', 'Bob,25']
data = [line.split(',') for line in csv_lines[1:]]
# Clean text file
with open('data.txt') as f:
clean_lines = [line.strip() for line in f if line.strip()]
Master list comprehensions to write more Pythonic, efficient code!