Python List Comprehensions

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 list
  • item โ€” the variable that takes each value from the iterable
  • iterable โ€” 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 # SyntaxError

So 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] # Error

So 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 idea

This 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.