Comprehensions
Comprehensions are a short and quick way to build new collections from data you already have. They let you write a loop, an optional filter, and a transformation, all in just one line, as long as the logic stays simple.
Why They Exist
Section titled “Why They Exist”Without a comprehension, you’d normally write a loop, maybe a condition, and then add each item one by one.
result = []for x in range(10): if x % 2 == 0: result.append(x**2)The same thing written in just one line:
result = [x**2 for x in range(10) if x % 2 == 0]The Main Idea
Section titled “The Main Idea”- A comprehension puts a loop, a filter, and a result expression all together in one line
- It cuts down on the extra setup code you’d normally write
- It works best when the transformation is simple and easy to understand at first glance
General Syntax
Section titled “General Syntax”[expression for item in iterable if condition]Breaking Down the Syntax
Section titled “Breaking Down the Syntax”| Part | What It Means |
|---|---|
expression | What you want to create |
item | The current item being looked at |
iterable | The collection you’re going through |
condition | An optional filter |
How It Actually Runs
Section titled “How It Actually Runs”List Comprehension
Section titled “List Comprehension”A list comprehension builds a brand new list from an existing collection.
squares = [x**2 for x in range(10)]Adding a Filter
Section titled “Adding a Filter”even_squares = [x**2 for x in range(10) if x % 2 == 0]The Same Thing Using a Normal Loop
Section titled “The Same Thing Using a Normal Loop”even_squares = []for x in range(10): if x % 2 == 0: even_squares.append(x**2)Using More Than One Loop
Section titled “Using More Than One Loop”pairs = [(x, y) for x in range(2) for y in range(2)]# Output: [(0, 0), (0, 1), (1, 0), (1, 1)]Choosing Between Two Values Inline
Section titled “Choosing Between Two Values Inline”labels = ["even" if x % 2 == 0 else "odd" for x in range(5)]Set Comprehension
Section titled “Set Comprehension”A set comprehension builds a set, which means any duplicate values automatically get removed.
unique_squares = {x**2 for x in range(10)}Good Times to Use This
Section titled “Good Times to Use This”- When you want to remove duplicate values
- When you want to quickly build a set for easy lookup
nums = [1, 2, 2, 3]unique = {x for x in nums} # {1, 2, 3}Dictionary Comprehension
Section titled “Dictionary Comprehension”A dictionary comprehension creates key-value pairs from a collection.
square_dict = {x: x**2 for x in range(5)}Adding a Filter
Section titled “Adding a Filter”filtered = {x: x**2 for x in range(10) if x % 2 == 0}Example
Section titled “Example”words = ["apple", "banana", "cherry"]length_map = {word: len(word) for word in words}Generator Expressions
Section titled “Generator Expressions”Generator expressions look like list comprehensions, but they use round brackets () instead of square brackets [].
Instead of building the whole result all at once, they give you one value at a time, only when you ask for it.
gen = (x**2 for x in range(10))The Big Difference
Section titled “The Big Difference”- A list comprehension builds the entire list right away
- A generator expression only creates each item when it’s actually needed
for value in gen: print(value)How They Use Memory
Section titled “How They Use Memory”Why They’re Often Faster
Section titled “Why They’re Often Faster”1. Less work happening behind the scenes in Python
Section titled “1. Less work happening behind the scenes in Python”- A regular loop usually involves several repeated steps that Python has to handle each time
- A comprehension keeps things tighter and simpler for Python to process
2. Fewer repeated steps
Section titled “2. Fewer repeated steps”# loop styleresult.append(x)
# comprehension style[x for x in iterable]3. Cleaner handling of variables
Section titled “3. Cleaner handling of variables”The variable you use inside a comprehension stays only inside that comprehension - it doesn’t spill out into the rest of your code.
A Performance Example
Section titled “A Performance Example”# Loopresult = []for x in range(1000000): result.append(x)
# Comprehensionresult = [x for x in range(1000000)]For simple tasks like this, the comprehension version is usually shorter to write and often runs faster too.
When You Should Use Them
Section titled “When You Should Use Them”- When the logic is short and straightforward
- When you’re just transforming or filtering one collection into another
- When the result naturally fits into a single line
When You Should Avoid Them
Section titled “When You Should Avoid Them”- When the logic has too many branches or conditions
- When you need several nested if-conditions
- When a regular loop would honestly be easier to read and fix if something goes wrong
An Example of Readability
Section titled “An Example of Readability”This is way too packed and confusing for a comprehension:
result = [x*y for x in range(10) for y in range(10) if x % 2 == 0 if y % 3 == 0]The loop version is much easier to read and follow:
result = []for x in range(10): if x % 2 != 0: continue for y in range(10): if y % 3 == 0: result.append(x*y)How Scope Works Inside Comprehensions
Section titled “How Scope Works Inside Comprehensions”x = 10lst = [x for x in range(5)]
print(x) # 10Comprehensions Inside Comprehensions (Nested)
Section titled “Comprehensions Inside Comprehensions (Nested)”matrix = [[i*j for j in range(3)] for i in range(3)]Output
Section titled “Output”[ [0, 0, 0], [0, 1, 2], [0, 2, 4],]Real-World Examples Where This Is Useful
Section titled “Real-World Examples Where This Is Useful”Filtering Out Data You Don’t Need
Section titled “Filtering Out Data You Don’t Need”users = [{"active": True}, {"active": False}]active_users = [u for u in users if u["active"]]Changing Data Into a New Form
Section titled “Changing Data Into a New Form”prices = [100, 200, 300]discounted = [p * 0.9 for p in prices]Turning a List of Lists Into One Flat List
Section titled “Turning a List of Lists Into One Flat List”matrix = [[1, 2], [3, 4]]flat = [num for row in matrix for num in row]