🌱BeginnerData Structures
List Comprehensions
Building lists concisely with Python's list comprehension syntax a core Pythonic idiom.
Overview
A list comprehension is a compact way to create a new list by applying an expression to each item in an iterable, optionally filtering items with a condition. It replaces the common pattern of creating an empty list, looping, and appending.
The syntax is: `[expression for item in iterable]` or with a filter: `[expression for item in iterable if condition]`.
Beyond lists, Python also has dict comprehensions `{k: v for k, v in items}`, set comprehensions `{expr for item in iterable}`, and generator expressions `(expr for item in iterable)` which are lazy (don't build a list in memory). All share the same basic syntax.
List comprehensions are fast (CPython has an optimized bytecode for them), readable when simple, and deeply Pythonic. However, avoid nesting more than two levels deep at that point a regular for loop is more readable.
Key Points
- •Basic: `[expr for item in iterable]` equivalent to a for loop that appends expr
- •With filter: `[expr for item in iterable if condition]` only includes items where condition is True
- •With transformation: `[x * 2 for x in numbers]` doubles each element
- •Nested: `[val for row in matrix for val in row]` flattens a 2D list
- •Dict comprehension: `{k: v for k, v in pairs}` or `{word: len(word) for word in words}`
- •Set comprehension: `{x % 5 for x in range(20)}` unique remainders
- •Generator expression: `(x**2 for x in range(10))` lazy, doesn't build a list in memory
Examples
Basic list comprehension vs for loop
# Traditional for loop
squares = []
for x in range(1, 6):
squares.append(x ** 2)
print(squares) # [1, 4, 9, 16, 25]
# Equivalent list comprehension same result, one line
squares = [x ** 2 for x in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]Filtering with an if clause
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Keep only even numbers
evens = [n for n in numbers if n % 2 == 0]
print(evens) # [2, 4, 6, 8, 10]
# Filter and transform together: square only odd numbers
odd_squares = [n**2 for n in numbers if n % 2 != 0]
print(odd_squares) # [1, 9, 25, 49, 81]Dict and set comprehensions
words = ["hello", "world", "python"]
# Dict comprehension: word → its length
word_lengths = {w: len(w) for w in words}
print(word_lengths) # {'hello': 5, 'world': 5, 'python': 6}
# Set comprehension: unique first letters
first_letters = {w[0] for w in words}
print(first_letters) # {'h', 'w', 'p'} (order may vary)
# Transform a dict
prices = {"apple": 1.2, "banana": 0.8, "cherry": 2.5}
discounted = {item: round(price * 0.9, 2) for item, price in prices.items()}
print(discounted)Common Mistakes
- Forgetting the expression comes before for: `[for x in lst x**2]` is wrong correct is `[x**2 for x in lst]`
- Over-nesting: `[val for row in matrix for val in row if val > 0]` starts becoming hard to read
- Using a comprehension for side effects (like printing) use a regular for loop for that
Note
A good rule of thumb: if your comprehension fits on one line and is readable, use it. If you need to add a comment to explain it, or it requires more than one nested for, switch to a regular for loop.
Exercises
Write Python code to solve each exercise. Run it in your browser and check your output.
Loading editor…
Completed: 0 / 5 exercises
Knowledge Check
Question 1 of 4