Comprehensions: Build Collections in a Pythonic Way
Introduction
In this chapter, you will learn Python comprehensions, a concise and powerful way to create lists, sets, and dictionaries. Comprehensions help you write cleaner collection-processing code than traditional loops in many cases. Once you understand them, your data transformation code becomes shorter and more readable.
Prerequisites
- Python
3.10+installed - Basic understanding of lists, sets, dictionaries, loops, and conditions
- Ability to run
.pyfiles in terminal or IDE
What Is a Comprehension
A comprehension is a compact syntax for building a new collection from an iterable.
Common types:
- list comprehension
- set comprehension
- dictionary comprehension
General idea:
[expression for item in iterable if condition]1) List Comprehension Basics
Create lists in one line.
# Create squares from 1 to 5
squares = [n * n for n in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]Equivalent loop version:
# Traditional loop style
squares = []
for n in range(1, 6):
squares.append(n * n)
print(squares)Both are valid, but comprehension is often cleaner for simple transformations.
2) List Comprehension with Conditions
You can filter data while building the list.
# Keep even numbers only
evens = [n for n in range(1, 11) if n % 2 == 0]
print(evens) # [2, 4, 6, 8, 10]You can also transform and filter together:
# Square only odd numbers
odd_squares = [n * n for n in range(1, 11) if n % 2 != 0]
print(odd_squares)3) Set Comprehension
Build sets directly with deduplication.
# Raw scores with duplicates
scores = [95, 88, 95, 76, 88, 92]
# Deduplicate and keep passing scores
passed_unique = {s for s in scores if s >= 60}
print(passed_unique)Set comprehension is useful for unique-value extraction.
4) Dictionary Comprehension
Build key-value mappings in one expression.
# Names and scores
names = ["Emma", "Liam", "Noah"]
scores = [95, 88, 92]
# Build name-score dictionary
score_map = {name: score for name, score in zip(names, scores)}
print(score_map)Dictionary filtering example:
# Keep only high scorers
high_scores = {name: score for name, score in score_map.items() if score >= 90}
print(high_scores)Tip
When Comprehension Works Best
Use comprehensions for short, clear transformations.
If logic becomes complex, switch to normal loops for readability.
5) Nested Comprehension (Beginner-Friendly Intro)
Nested comprehensions can generate matrix-like data.
# Build multiplication pairs
pairs = [(x, y) for x in range(1, 4) for y in range(1, 4)]
print(pairs)This equals nested loops:
- loop
x - loop
y - append
(x, y)
6) Real Mini Example: Student Data Cleaner
This example uses multiple comprehension types in one script.
# Raw student score records
records = [
{"name": "Emma", "score": 95},
{"name": "Liam", "score": 58},
{"name": "Noah", "score": 88},
{"name": "Olivia", "score": 73},
]
# Build passing student name list
passed_names = [r["name"] for r in records if r["score"] >= 60]
# Build score dictionary
score_map = {r["name"]: r["score"] for r in records}
# Build unique score set
unique_scores = {r["score"] for r in records}
print("Passed names:", passed_names)
print("Score map:", score_map)
print("Unique scores:", unique_scores)This pattern appears frequently in ETL scripts, API preprocessing, and reporting.
Warning
Avoid deeply nested comprehensions with complicated conditions.
Readable code is always better than clever code.
Common Beginner Mistakes
Mistake 1: Over-Compacting Logic
Trying to put too much logic in one line makes code hard to debug.
Mistake 2: Forgetting Collection Type
[] creates list, {} with key-value creates dict, {} with one expression creates set.
Mistake 3: Using Comprehension When Side Effects Are Needed
For print-heavy or multi-step operations, regular loops are usually clearer.
Surprise Practice Challenge
Build a "Mini Classroom Analyzer" with comprehensions:
- Given student records (
name,math,english) - Create a list of students whose math score >= 90
- Create a dictionary of
name -> average score - Create a set of all distinct english scores
- Print results clearly
If you finish this, you can handle real collection transformations elegantly.
FAQ
Are comprehensions faster than loops?
Often they are efficient, but the biggest advantage is concise and expressive code for simple transformations.
Should I always use comprehensions?
No. Use them when they improve readability; otherwise use standard loops.
Can I use if-else inside list comprehension?
Yes. Example: [x if x > 0 else 0 for x in values].
How do I decide between list/set/dict comprehension?
Choose based on the target data structure you need at the end.