List comprehensions provide a concise way to create lists in Python. They're more readable and often faster than traditional for loops.
Basic Syntax
The basic syntax of a list comprehension is:
# Traditional approach
squares = []
for x in range(10):
squares.append(x**2)
# List comprehension approach
squares = [x**2 for x in range(10)]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
With Conditions
You can add conditions to filter elements:
# Get even numbers only
evens = [x for x in range(20) if x % 2 == 0]
print(evens) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# Multiple conditions
filtered = [x for x in range(50) if x % 2 == 0 if x % 5 == 0]
print(filtered) # [0, 10, 20, 30, 40]
Nested List Comprehensions
Create matrices and flatten lists:
# Create a 3x3 matrix
matrix = [[i*3+j for j in range(3)] for i in range(3)]
print(matrix) # [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
# Flatten a matrix
flattened = [num for row in matrix for num in row]
print(flattened) # [0, 1, 2, 3, 4, 5, 6, 7, 8]
List comprehensions make your code more Pythonic and easier to read once you're familiar with the syntax!