What Are List Comprehensions?
List comprehensions provide a concise way to create lists. They replace verbose for-loops with a single, readable line of code.
Basic Syntax
# Traditional for-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]
Adding Conditions
# Filter even numbers
evens = [x for x in range(20) if x % 2 == 0]
# If-else (expression comes before the if)
labels = ['even' if x % 2 == 0 else 'odd' for x in range(5)]
# ['even', 'odd', 'even', 'odd', 'even']
Nested Comprehensions
# 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]
Dict and Set Comprehensions
# Dictionary comprehension
names = ['Alice', 'Bob', 'Charlie']
name_lengths = {name: len(name) for name in names}
# {'Alice': 5, 'Bob': 3, 'Charlie': 7}
# Invert a dictionary
inverted = {v: k for k, v in original.items()}
Real-World Examples
# Clean and transform data
raw_prices = [' $19.99 ', '$24.50', '$invalid', '$32.00 ']
clean_prices = [
float(p.strip().replace('$', ''))
for p in raw_prices
if p.strip().replace('$', '').replace('.', '').isdigit()
]
print(clean_prices) # [19.99, 24.5, 32.0]