List Comprehensions
List Comprehensions
Section titled “List Comprehensions”What it is
Section titled “What it is”List comprehensions provide a concise way to create lists by applying an expression to each item in an iterable, optionally filtering items. They’ve been in Python since version 2.0.
Before this feature
Section titled “Before this feature”Required explicit loops to build lists:
# Traditional loopsquares = []for x in range(10): squares.append(x ** 2)
# Filteringevens = []for x in range(10): if x % 2 == 0: evens.append(x)After this feature
Section titled “After this feature”List comprehensions provide one-liner solutions:
# Basic comprehensionsquares = [x ** 2 for x in range(10)]
# With filteringevens = [x for x in range(10) if x % 2 == 0]
# Transform and filterwords = ["hello", "world", "python"]upper_long = [w.upper() for w in words if len(w) > 5]
# Nested comprehensionsmatrix = [[i * j for j in range(3)] for i in range(3)]# [[0, 0, 0], [0, 1, 2], [0, 2, 4]]
# Multiple conditionsnumbers = [x for x in range(50) if x % 2 == 0 if x % 3 == 0]
# Using multiple iterablespairs = [(x, y) for x in range(3) for y in range(3)]
# Dictionary comprehensionsquares_dict = {x: x ** 2 for x in range(5)}
# Set comprehensionunique_lengths = {len(word) for word in words}Why this is better
Section titled “Why this is better”- Concise: One line instead of multiple
- Readable: Clear intent (when not overused)
- Faster: Often faster than equivalent loops
- Pythonic: Idiomatic Python style
- Functional: Encourages immutable patterns
Key notes / edge cases
Section titled “Key notes / edge cases”- Don’t sacrifice readability for conciseness
- Can be slower for very complex expressions
- Creates entire list in memory (use generators for large data)
- Can become hard to read when nested or with multiple conditions
- Alternative comprehensions: dict, set, generator
# Generator expression (lazy evaluation)squares_gen = (x ** 2 for x in range(1000000))
# Flattening nested listsnested = [[1, 2], [3, 4], [5, 6]]flat = [item for sublist in nested for item in sublist]# [1, 2, 3, 4, 5, 6]
# Conditional expressionsvalues = [x if x >= 0 else 0 for x in [-1, 2, -3, 4]]# [0, 2, 0, 4]
# Too complex (BAD)result = [ process(x, y, z) for x in range(100) if validate(x) for y in get_ys(x) if check(y) for z in get_zs(y)]# Better: use regular loops for readabilityQuick practice
Section titled “Quick practice”-
Create a list of squares for numbers 1 to 10
Answer
squares = [x ** 2 for x in range(1, 11)] -
Extract even numbers from
[1, 2, 3, 4, 5, 6, 7, 8]Answer
evens = [x for x in [1, 2, 3, 4, 5, 6, 7, 8] if x % 2 == 0] -
Convert
["apple", "banana", "cherry"]to uppercaseAnswer
upper_fruits = [fruit.upper() for fruit in ["apple", "banana", "cherry"]]