Comprehensions
List, dict, and set comprehensions — Python's concise data transformation syntax
Free tier: read the explanation here. Upgrade to Pro for Drills, Speed challenges & Mastery badges.
UpgradeKnowledge Debt detected
You can study this freely — but your score may plateau if these foundations have gaps. The Mastery badge requires them to be solid.
Explanation
s create collections in a single readable line.
List comprehension:
python # [expression for item in iterable if condition] squares = [x**2 for x in range(10)] evens = [x for x in range(20) if x % 2 == 0] upper = [s.upper() for s in ['hello', 'world']]
Dict comprehension:
python # {key: value for item in iterable} word_lengths = {word: len(word) for word in ['apple', 'banana', 'kiwi']} # {'apple': 5, 'banana': 6, 'kiwi': 4}
Set comprehension:
python unique_lengths = {len(word) for word in ['cat', 'dog', 'fish', 'ant']} # {3, 4} — deduplicated
Nested comprehension:
python matrix = [[row * col for col in range(1, 4)] for row in range(1, 4)] # [[1,2,3], [2,4,6], [3,6,9]]
When NOT to use them: If the logic is complex enough to need a comment, use a regular loop for readability.
Examples
Practical dict comprehension
Dict comprehensions from .items() is a common pattern
# Build a lookup from a list of dicts
users = [{'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bob'}]
user_map = {u['id']: u['name'] for u in users}
print(user_map) # {1: 'Alice', 2: 'Bob'}
# Filter: only adult ages
ages = {'Alice': 25, 'Bob': 16, 'Carol': 30}
adults = {name: age for name, age in ages.items() if age >= 18}
print(adults) # {'Alice': 25, 'Carol': 30}How well did you understand this?
Next in Python Core
Generators