Complete Python Series · Part 13 of 29
Python Comprehensions | List, Dictionary & Set Comprehensions
Master Python Comprehensions (List, Dictionary and Set)
Prefer watching over reading? Watch this lesson on YouTube →
Up to now we have written Python the traditional way: create an empty list, loop over the data, and append() the result one item at a time. That works in every language. But Python has its own, shorter way of doing these everyday jobs, and experienced Python developers use it all the time. This is called Pythonic programming.
Today we start this course, Pythonic Programming Techniques, and cover the first three topics:
- ** List comprehension:** build a new list in one line
- ** Comprehension filtering:** keep only the items you want, or choose between two values
- ** Dictionary and set comprehensions:** the same idea with
{ }
List Comprehension
What is a list comprehension?
A list comprehension is a shorter way to create a list. It combines a for loop and list creation into a single line.
- It is mostly used to transform existing data into new data.
- It removes repetitive code (no empty list, no
append()). - It always creates a new list. The original list is never changed.
The traditional approach: a for loop
Say we have the numbers 1 to 5 and want a list of their squares: 1, 4, 9, 16, 25.
numbers = [1, 2, 3, 4, 5]
squares = []
for num in numbers:
squares.append(num ** 2)
print(squares) # [1, 4, 9, 16, 25]
The steps are always the same:
- Create an empty list.
- Loop through the original list.
- Process each element.
- Add the result using
append().
The limitation: we need several lines for what is really one simple operation, "square every number".
The same thing with a list comprehension
numbers = [1, 2, 3, 4, 5]
squares = [num ** 2 for num in numbers]
print(squares) # [1, 4, 9, 16, 25]
Read it out loud: "num squared, for every num in numbers." Python goes into numbers, takes one number at a time, squares it, and puts it into a brand new list.
List comprehension syntax
[expression for item in iterable]
Tip: when writing one, ask yourself two questions:
- What do I want to store? That is your expression.
- Where do the items come from? That is your iterable.
For squares: store x ** 2, items come from numbers, so it becomes [x ** 2 for x in numbers].
Transforming data
The expression is not limited to maths. You can use string methods and function calls too. Each element is processed on its own.
names = ["anuj", "yogesh", "damanpreet"]
result = [name.upper() for name in names]
print(result) # ['ANUJ', 'YOGESH', 'DAMANPREET']
With a loop this would be an empty list, a loop and an append(). Here it is one line: think about the item, and think about what transformation you want on that item.
Changing data types (mapping)
A very common real-world case: you get data from a network call or a server, and it is in the wrong type. For example, years arrive as integers but you need them as strings.
years = [1994, 1999, 2001, 2008, 1992]
labels = [str(year) for year in years]
print(labels) # ['1994', '1999', '2001', '2008', '1992']
- Input and output types can be different (
intin,strout). - Useful for converting data formats.
- This operation is commonly called mapping.
Performance and readability
List comprehensions are usually faster than the equivalent for loop. Not always, but generally. Why?
In a loop, every iteration runs squares.append(...). That means Python has to:
- Look up the
appendmethod on the list object, and - Call it.
Those are extra steps, repeated for every single item. A list comprehension is the Pythonic way, so Python has already optimised it: items are added to the new list directly, with no append lookup.
You can see this yourself with the dis module, which shows the bytecode instructions behind a function:
import dis
def f1(numbers): # traditional loop
squares = []
for n in numbers:
squares.append(n ** 2)
return squares
def f2(numbers): # list comprehension
return [n ** 2 for n in numbers]
dis.dis(f1) # look for LOAD_ATTR (append) + CALL inside the loop
dis.dis(f2) # look for LIST_APPEND, no append attribute lookup
Summary:
- Usually faster than equivalent
forloops. - Avoids explicitly calling
append()in every iteration. - Uses less code for simple transformations.
- Prefer comprehensions for straightforward logic.
- Use regular loops when the logic becomes complex.
Why does this syntax even exist? Python is used heavily for data engineering, ML and automation, where people transform lists of data all day. A common pattern got its own short, optimised syntax. That is the whole idea behind "Pythonic" code.
Comprehension Filtering
Filtering with if
Sometimes you don't want every element, only the ones that pass a condition. Add an if after the for clause.
[expression for item in iterable if condition]
- Used to select specific elements from a collection.
- Only elements that satisfy the condition are included.
- The resulting list can be shorter than the original.
Example: from a list of response times, keep only the slow ones (above 110).
times = [50, 120, 80, 200, 150]
slow = [t for t in times if t > 110]
print(slow) # [120, 200, 150]
For every t, Python checks t > 110. If it is True, t goes into the new list. If it is False, it is skipped.
Conditional expression (if-else)
What if you don't want to remove anything, but instead choose a value for each element? Then you use if-else, and it goes before the for clause.
[expr_if_true if condition else expr_if_false for item in iterable]
Example: mark each score as pass or fail (pass mark is above 40).
scores = [90, 92, 80, 64, 32, 98, 30]
result = ["pass" if score > 40 else "fail" for score in scores]
print(result)
# ['pass', 'pass', 'pass', 'pass', 'fail', 'pass', 'fail']
- Used to choose an output value based on a condition.
- Write
if-elsebefore theforclause. - Every input produces one output.
- No elements are removed. The output list is the same size as the input.
Remember the difference: filtering
ifremoves unwanted elements, whereas conditionalif-elsereplaces values.
Flattening nested lists
A nested list (a list of lists) often needs to become one flat list:
[[1, 2], [3, 4], [5, 6]] -> [1, 2, 3, 4, 5, 6]
With normal loops you need two loops, one inside the other:
mat = [[1, 2], [3, 4], [5, 6]]
flat = []
for group in mat:
for item in group:
flat.append(item)
print(flat) # [1, 2, 3, 4, 5, 6]
A comprehension can use multiple for clauses. Write them in the same order as the nested loops: outer loop first, inner loop second.
mat = [[1, 2], [3, 4], [5, 6]]
flat = [item for group in mat for item in group]
print(flat) # [1, 2, 3, 4, 5, 6]
- Used to convert a nested list into a single list.
- Requires multiple
forclauses. - The first loop selects an inner list.
- The second loop extracts its elements.
- The order of elements is preserved.
Try it: build a big matrix (say 1,000 x 1,000), flatten it once with nested loops and once with a comprehension, and time both using
time.time()before (t1) and after (t2). Compare the difference.
Nested loops for combinations
Two independent for clauses also give you every possible pair. For example, all colour and size combinations for a T-shirt:
colors = ["Black", "White"]
sizes = ["S", "M", "L", "XL", "XXL"]
pairs = [(c, s) for c in colors for s in sizes]
print(pairs)
# [('Black', 'S'), ('Black', 'M'), ('Black', 'L'), ('Black', 'XL'), ('Black', 'XXL'),
# ('White', 'S'), ('White', 'M'), ('White', 'L'), ('White', 'XL'), ('White', 'XXL')]
The result is a list of tuples.
- Used to generate all possible pairs.
- Uses multiple independent
forclauses. - Each element of the first list pairs with every element of the second.
- Total combinations =
len(list1) * len(list2). Here, 2 x 5 = 10.
The readability limit
Comprehensions are great, but don't force everything into one line. Take this task: from a matrix, collect only the numbers that are positive and even.
matrix = [[1, 2], [3, -4], [5, 6]]
# One line, but hard to read
result = [n for row in matrix for n in row if n > 0 and n % 2 == 0]
# Clear and easy to follow
result = []
for row in matrix:
for n in row:
if n > 0 and n % 2 == 0:
result.append(n)
print(result) # [2, 6]
Both give [2, 6], but the second version is much easier to understand.
- Avoid overly complex comprehensions.
- Too many loops and conditions make code harder to understand.
- Prefer normal loops for complicated logic.
- Readability is more important than writing fewer lines. In a real company's production code, readable code wins.
Dictionary and Set Comprehensions
The same idea works for sets and dictionaries. The only visible change is the brackets: { } instead of [ ].
Set comprehensions
{expression for item in iterable}
Example: you have a list of tags with mixed capitalisation and duplicates, and you want the unique tags in lowercase.
The traditional way:
tags = ["Python", "Java", "python", "JAVA"]
unique_tags = set()
for tag in tags:
unique_tags.add(tag.lower())
print(unique_tags) # {'python', 'java'}
With a set comprehension:
tags = ["Python", "Java", "python", "JAVA"]
unique_tags = {word.lower() for word in tags}
print(unique_tags) # {'python', 'java'}
Python lowercases "Python" and adds it. Then "Java" becomes "java" and is added. When "python" comes again, it is already in the set, so nothing new is added. Same for "JAVA".
- Creates a set using a single line.
- Uses curly braces.
- Automatically removes duplicate values.
- Supports transformations and filtering.
- Set elements must be hashable (immutable values like strings, numbers and tuples).
- Sets have no fixed order, so the printed order may differ.
Dictionary comprehensions
{key: value for item in iterable}
The difference from a set comprehension: instead of one expression, you give a key and a value.
Example: map each fruit to the length of its name.
The traditional way:
fruits = ["apple", "banana", "mango"]
lengths = {}
for fruit in fruits:
lengths[fruit] = len(fruit)
print(lengths) # {'apple': 5, 'banana': 6, 'mango': 5}
With a dictionary comprehension:
fruits = ["apple", "banana", "mango"]
lengths = {fruit: len(fruit) for fruit in fruits}
print(lengths) # {'apple': 5, 'banana': 6, 'mango': 5}
- Creates a dictionary in one line.
- Uses
{key: value}syntax. - Generates one key-value pair for each iteration.
- Useful for creating lookup tables.
- Duplicate keys overwrite earlier values. If
"apple"appeared twice, the later value would replace the earlier one.
Creating dictionaries using zip()
Often the keys and values are in two separate lists. zip() pairs them up by position:
l1 = [1, 2, 3]
l2 = [4, 5, 6]
print(list(zip(l1, l2))) # [(1, 4), (2, 5), (3, 6)]
So you can build a dictionary like this:
keys = ["name", "age", "city"]
values = ["Nitin", 20, "Bhopal"]
data = {k: v for k, v in zip(keys, values)}
print(data) # {'name': 'Nitin', 'age': 20, 'city': 'Bhopal'}
# Shortcut: dict() can take the zipped pairs directly
data2 = dict(zip(keys, values))
print(data2) # {'name': 'Nitin', 'age': 20, 'city': 'Bhopal'}
zip()combines elements from multiple iterables.- It pairs elements based on their positions.
- Useful for converting two lists into a dictionary.
- It stops when the shortest iterable ends.
print(list(zip([1, 2, 3], [4, 5]))) # [(1, 4), (2, 5)] the 3 is dropped
Inverting a dictionary
Sometimes you have code -> country but need country -> code. Swap the keys and values:
codes = {
"IN": "India",
"US": "USA",
"JP": "Japan",
}
reverse = {country: code for code, country in codes.items()}
print(reverse) # {'India': 'IN', 'USA': 'US', 'Japan': 'JP'}
codes.items() gives each pair as a tuple, like ("IN", "India"). We unpack it into code, country and write it back the other way round.
- Swaps the keys and values.
- Uses
.items()to access existing pairs. - Useful for reverse lookups.
- Original values must be hashable, because they become keys.
- Duplicate original values cause key collisions: only the last one survives.
Quick Recap
Key takeaways:
- A comprehension = loop + collection creation in one line. It always creates a new collection.
- Filter
ifgoes afterforand removes items.if-elsegoes beforeforand replaces values. - Multiple
forclauses follow the same order as nested loops. - Comprehensions are usually faster because they skip the
append()lookup and call. - If it gets hard to read, use a normal loop. Readability beats fewer lines.
Practice
- Given
nums = [3, 8, 11, 14, 20], create a list of only the even numbers, each multiplied by 10. - Given
marks = [35, 78, 42, 90, 28], create a list where each mark becomes"pass"(40 and above) or"fail". - Flatten
[[1, 2, 3], [4, 5], [6]]into one list using a comprehension. - From
matrix = [[1, -2], [3, -4], [5, 6]], collect the positive even numbers. Write it both as a loop and as a comprehension. Which one is easier to read? - Given
words = ["Hi", "hello", "HI", "Hello", "hey"], create a set of unique lowercase words. - Given
students = ["Asha", "Rohit", "Meera"]andscores = [88, 72, 95], build a dictionary usingzip(), then invert it.
What's Next
In the next part we continue Pythonic programming with map() and filter(), the functional way of doing what we did with comprehensions today.