Useful Data Tips

Python List Comprehensions: Write Faster, Cleaner Code

⏱️ 30 sec read 🐍 Python

List comprehensions are 2-3x faster than for loops and make your code more Pythonic. Here's how to use them effectively:

Basic Syntax

# Traditional loop ❌
result = []
for x in range(10):
    result.append(x ** 2)

# List comprehension ✅
result = [x ** 2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

With Conditionals

# Filter even numbers
evens = [x for x in range(20) if x % 2 == 0]
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

# If-else inside comprehension
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]
# [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Create combinations
pairs = [(x, y) for x in [1, 2, 3] for y in ['a', 'b']]
# [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b'), (3, 'a'), (3, 'b')]

String Operations

# Process strings
words = ['hello', 'world', 'python']
upper = [w.upper() for w in words]
# ['HELLO', 'WORLD', 'PYTHON']

# Filter by length
long_words = [w for w in words if len(w) > 5]
# ['python']

# Extract first letters
initials = [w[0] for w in words]
# ['h', 'w', 'p']

Dictionary & Set Comprehensions

# Dictionary comprehension
squares = {x: x ** 2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

# Set comprehension (unique values)
unique_lengths = {len(w) for w in ['cat', 'dog', 'bird', 'fox']}
# {3, 4}

# Invert dictionary
original = {'a': 1, 'b': 2, 'c': 3}
inverted = {v: k for k, v in original.items()}
# {1: 'a', 2: 'b', 3: 'c'}

Practical Examples

# Parse CSV data
data = "name,age,city\nJohn,25,NYC\nJane,30,LA"
rows = [line.split(',') for line in data.split('\n')[1:]]

# Extract specific fields
names = [row[0] for row in rows]

# Filter data
adults = [row for row in rows if int(row[1]) >= 18]

# Transform filenames
files = ['data.csv', 'report.xlsx', 'image.png']
basenames = [f.split('.')[0] for f in files]
# ['data', 'report', 'image']

Performance Tips

Pro Tip: If your comprehension spans multiple lines or becomes hard to read, convert it to a regular for loop. Readability beats cleverness.

← Back to Python Tips