Python Tutorial / Build List, Dictionary and Set Comprehensions
A comprehension creates a collection by transforming items or selecting those that match a condition. Use it for a short, readable transformation; prefer a normal loop for multiple processing steps, exception handling or side effects.
Separate transformation from filtering
The list form is [expression for item in source if condition]. The trailing if decides whether to include an item. An expression such as a if condition else b instead chooses the value for an included item.
A comprehension does not mutate the outer source collection, but its expressions determine which existing objects remain shared. Creating a new list does not automatically clone dictionaries or lists nested inside it.
For the relevant APIs and platform requirements, see Build List, Dictionary and Set Comprehensions documentation.
Create three kinds of collection
Save the complete code below as comprehensions.py in a separate practice folder, using UTF-8. Run python comprehensions.py in a terminal with your project virtual environment selected. Outside a virtual environment on macOS or Ubuntu, use python3 when that is your interpreter command.
amounts = [3500, -1, 8000, 0]
valid = [x for x in amounts if x >= 0]
labels = ["paid" if x > 0 else "free" for x in valid]
records = [("food", 3500), ("bus", 2500)]
by_name = {name: amount for name, amount in records}
remainders = {x % 3 for x in valid}
print(valid)
print(labels)
print(by_name)
print(sorted(remainders))
Expected output:
[3500, 8000, 0]
['paid', 'paid', 'free']
{'food': 3500, 'bus': 2500}
[0, 2]
Account for duplicate keys and values
In a dictionary comprehension, a later value for the same key replaces an earlier one. {category: amount for ...} therefore does not calculate category totals. A set comprehension removes duplicates, so its size may be smaller than the number of source records.
First express a rule correctly as a normal loop, then ask whether a single transformation or filter improves its readability. A deeply nested comprehension can be difficult to maintain even when it occupies fewer lines.
Check empty results and avoid side effects
If every item is excluded, the result is empty. Decide what that means before reading its first item or dividing by its length. Do not use a list comprehension merely to print or save files; a for loop makes those side effects explicit without creating an unused result list.
- Change the numeric filter from >= 0 to > 0 and verify that zero disappears.
- Add another record with the same name and observe replacement in the dictionary.
- Restore the inputs and explain why a category total requires accumulation rather than simple key construction.
The dictionary totals example provides a clear accumulation loop when repeated keys should combine instead of overwrite.




