Python List Comprehensions
Table of Contents
In the last lesson, we learned about Python List Slicing. Now letโs build new lists with short, clear expressions.
๐งฉ Letโs Talk About a Shortcut
We know how to create a list. We know how to loop through a list. We know how to add items to a list.
But sometimes, we want to create a new list based on an existing one. Maybe we want to square every number. Maybe we want to filter out the negative numbers. Maybe we want to convert every string to uppercase.
We could write a loop. And that works. But it takes a few lines. And it is a bit repetitive.
Python has a shortcut for this. It is called a list comprehension.
๐ What Is a List Comprehension in Python?
A list comprehension is a way to create a list in one line. We describe what we want. And Python builds the list for us.
It is like giving a recipe. Instead of saying โtake this, do that, add it to a listโ step by step, we just say what the final list should look like.
๐ง The Basic Syntax of Python List Comprehension
[expression for item in iterable]expressionโ what we want to put in the listitemโ the variable that takes each value from the iterableiterableโ the sequence we are looping over (list, string, range, etc.)
Letโs see a simple example.
numbers = [1, 2, 3, 4, 5]squares = [n * n for n in numbers]print(squares)Output
[1, 4, 9, 16, 25]That is it. One line. It took each number, squared it, and put it in a new list.
Compare that to the loop version:
numbers = [1, 2, 3, 4, 5]squares = []for n in numbers: squares.append(n * n)print(squares)Both do the same thing. The list comprehension is shorter and cleaner.
๐ Adding a Condition to Python List Comprehension
We can add an if to filter items. Only items that satisfy the condition are included.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]evens = [n for n in numbers if n % 2 == 0]print(evens)Output
[2, 4, 6, 8, 10]The if n % 2 == 0 part is the filter. Only even numbers pass through.
We can use any condition.
words = ["apple", "banana", "cherry", "date"]long_words = [w for w in words if len(w) > 5]print(long_words)Output
['banana', 'cherry']๐ If and else in Python List Comprehension
We can also use if and else together. But the syntax is a bit different. The if-else goes before the for.
numbers = [1, 2, 3, 4, 5]labels = ["even" if n % 2 == 0 else "odd" for n in numbers]print(labels)Output
['odd', 'even', 'odd', 'even', 'odd']Here, for each number, we choose โevenโ or โoddโ. The condition is n % 2 == 0. If true, โevenโ. If false, โoddโ.
That is the ternary operator inside a comprehension. It is allowed. But letโs not make it too complex.
โ๏ธ Nested Comprehensions in Python
We can have a comprehension inside a comprehension. But letโs be careful. It can get confusing.
matrix = [[1, 2], [3, 4], [5, 6]]flattened = [num for row in matrix for num in row]print(flattened)Output
[1, 2, 3, 4, 5, 6]That flattens a list of lists into a single list.
We can read it as: for each row in matrix, for each num in row, add num.
The order is from left to right. The first for is the outer loop. The second for is the inner loop.
We can also add conditions.
matrix = [[1, 2], [3, 4], [5, 6]]evens = [num for row in matrix for num in row if num % 2 == 0]print(evens)Output
[2, 4, 6]๐ก When to Use Python List Comprehensions
Use them when:
- We are creating a new list from an existing iterable.
- The logic is simple (one expression, maybe one condition).
- We want cleaner, more readable code.
Do not use them when:
- The logic is complex.
- We need multiple statements.
- The comprehension becomes hard to read.
Letโs remember, readability matters more than shortness. If a loop is clearer, use a loop.
๐งช Python List Comprehension: A Real-Life Example
Letโs say we have a list of temperatures in Celsius. And we want to convert them to Fahrenheit.
celsius = [0, 10, 20, 30, 40]fahrenheit = [(c * 9/5) + 32 for c in celsius]print(fahrenheit)Output
[32.0, 50.0, 68.0, 86.0, 104.0]That is clean and easy.
Another example: reading a list of names and capitalizing them.
names = ["alex", "sam", "john"]capitalized = [name.capitalize() for name in names]print(capitalized)Output
['Alex', 'Sam', 'John']โ ๏ธ A Quick Note on Performance
List comprehensions are often faster than writing a loop with append(). Because Python optimizes them internally. So they are not just shorter, they are also efficient.
But letโs not use them just for speed. Letโs use them when they make the code clearer.
๐๏ธ Common Mistakes with Python List Comprehensions
โ Mistake 1: Forgetting the Brackets
squares = n * n for n in numbers # SyntaxErrorSo what do we do? We wrap it in square brackets.
squares = [n * n for n in numbers]๐ซ Mistake 2: Using the Wrong Order for if-else
labels = [if n % 2 == 0 "even" else "odd" for n in numbers] # ErrorSo what do we do? We put the expression first.
labels = ["even" if n % 2 == 0 else "odd" for n in numbers]๐ Mistake 3: Trying to Do Too Much
result = [x * y + z for x in list1 for y in list2 for z in list3 if x > 0 if y < 10 if z != 0]This is technically valid but unreadable. Letโs break it into smaller steps or use loops.
๐ Mistake 4: Modifying the Original List Inside a Comprehension
numbers = [1, 2, 3][numbers.append(4) for _ in range(3)] # Bad ideaThis modifies the list while iterating. And it returns a list of None. Letโs not do this. Comprehensions are for creating new lists, not for side effects.
๐ A Real-Life Example with Conditions
Letโs filter a list of words to only those that start with a vowel.
words = ["apple", "banana", "orange", "grape", "umbrella"]vowel_words = [w for w in words if w[0].lower() in "aeiou"]print(vowel_words)Output
['apple', 'orange', 'umbrella']That is a nice one-liner.
Next, we will learn about Python Nested Lists and work with lists stored inside other lists.