List, Dictionary and Set Comprehensions: Writing Pythonic Code
One of the most common patterns in programming is taking an existing collection of items, filtering out the ones you do not want, applying a transformation to the rest and storing the result in a new collection. Instead of writing a four-line for loop with .append() every time, Python offers a concise, high-speed syntax known as a comprehension.
Anatomy of a List Comprehension
A list comprehension combines the loop and the element creation inside square brackets:
# Syntax: [expression for item in iterable if condition]
response_times = [45, 120, 85, 310, 22, 190]
# Traditional loop approach
slow_requests = []
for ms in response_times:
if ms > 100:
slow_requests.append(ms)
# Equivalent List Comprehension (one clean line)
slow_requests = [ms for ms in response_times if ms > 100]
print(slow_requests) # [120, 310, 190]
Transforming AND Filtering Together
You can clean or transform each item in the left-hand expression while filtering on the right:
raw_usernames = [" Alice ", "BOB", "", " charlie_admin ", " "]
# Strip spaces and lowercase, keeping only non-empty strings
clean_users = [u.strip().lower() for u in raw_usernames if u.strip()]
print(clean_users) # ['alice', 'bob', 'charlie_admin']
Dictionary and Set Comprehensions
The exact same pattern works with curly braces to build dictionaries ({k: v for ...}) and sets ({expr for ...}):
| Type | Syntax Pattern | Practical Example |
|---|---|---|
| List Comprehension | [expr for x in iter] |
[x * 2 for x in range(5)] → [0, 2, 4, 6, 8] |
| Dict Comprehension | {k: v for x in iter} |
{host: 8080 for host in ["web1", "web2"]} |
| Set Comprehension | {expr for x in iter} |
{email.split("@")[1] for email in emails} (unique domains) |
A Short Example: Inverting and Filtering a Server Inventory
# Mapping of server -> disk usage percentage
disk_usage = {
"srv-web-01": 45,
"srv-db-01": 92,
"srv-cache-01": 88,
"srv-worker-01": 61
}
# Build a new dictionary of ONLY servers exceeding 85% disk usage
alerts = {host: f"{pct}% FULL" for host, pct in disk_usage.items() if pct >= 85}
print(alerts)
# Output: {'srv-db-01': '92% FULL', 'srv-cache-01': '88% FULL'}
When NOT to Use a Comprehension
Readability always comes first in Python. Avoid comprehensions when:
- The logic requires nested loops more than two levels deep.
- You need exception handling (
try/except) inside the loop. - You are only performing a side effect (like printing or writing to a database) without needing the resulting list. Never write
[print(x) for x in items]—that creates a useless list of[None, None, ...]in memory.
Key takeaways
- List comprehensions (
[expr for item in iterable if condition]) replace verbose loop-and-append boilerplate. - Dictionary comprehensions (
{k: v for ...}) and set comprehensions ({x for ...}) follow the exact same structure. - Keep comprehensions simple; if an expression wraps across multiple complex lines, use a regular
forloop instead.