Python List Comprehension: Write Cleaner Code with Practical Examples

If you've been learning Python, you've probably written code like this:

numbers = [1, 2, 3, 4, 5] squares = [] for number in numbers: squares.append(number ** 2) print(squares) 

Output:

[1, 4, 9, 16, 25] 

There's nothing wrong with this code.

But Python gives us a shorter and often more readable way to create the same list:

numbers = [1, 2, 3, 4, 5] squares = [number ** 2 for number in numbers] print(squares) 

Same result. Much less code.

Welcome to list comprehensions.

In this beginner-friendly guide, we'll understand their syntax, use conditions, compare them with regular loops, and look at situations where you should not use them.

What Is a List Comprehension?

A list comprehension is a concise way to create a new list from an iterable such as another list, tuple, or range.

The basic syntax is:

[expression for item in iterable] 

For example:

numbers = [1, 2, 3, 4] doubled = [x * 2 for x in numbers] print(doubled) 

Output:

[2, 4, 6, 8] 

Let's break this down:

x * 2 

is the value we want to add to the new list.

for x in numbers 

loops through every value in numbers.

So Python essentially reads it as:

For every x in numbers, calculate x * 2 and put the result into a new list.

Regular Loop vs List Comprehension

Here's a traditional loop:

numbers = [1, 2, 3, 4, 5] squares = [] for x in numbers: squares.append(x * x) 

Using list comprehension:

squares = [x * x for x in numbers] 

Both approaches create the same result:

[1, 4, 9, 16, 25] 

The list comprehension is shorter, but shorter doesn't automatically mean better.

Readability should always come first.

Filtering Values with if

List comprehensions become even more useful when we add conditions.

Suppose we only want even numbers.

Traditional approach:

numbers = [1, 2, 3, 4, 5, 6] evens = [] for x in numbers: if x % 2 == 0: evens.append(x) print(evens) 

We can write the same logic as:

numbers = [1, 2, 3, 4, 5, 6] evens = [x for x in numbers if x % 2 == 0] print(evens) 

Output:

[2, 4, 6] 

The pattern becomes:

[expression for item in iterable if condition] 

Transform and Filter at the Same Time

You can also transform only the values that match a condition.

For example, let's square only the even numbers:

numbers = [1, 2, 3, 4, 5, 6] even_squares = [ x ** 2 for x in numbers if x % 2 == 0 ] print(even_squares) 

Output:

[4, 16, 36] 

Here Python first checks whether the number is even and then calculates its square.

Using if-else

There's an important syntax difference when you need both if and else.

Suppose we want to label numbers as even or odd:

numbers = [1, 2, 3, 4] labels = [ "Even" if x % 2 == 0 else "Odd" for x in numbers ] print(labels) 

Output:

['Odd', 'Even', 'Odd', 'Even'] 

Notice where the condition appears:

"Even" if condition else "Odd" 

comes before the for.

Compare these two patterns:

Filtering

[x for x in numbers if x > 5] 

Conditional transformation

["Even" if x % 2 == 0 else "Odd" for x in numbers] 

This difference is a common source of confusion for beginners.

Working with Strings

List comprehensions aren't limited to numbers.

languages = ["python", "javascript", "php"] uppercase = [language.upper() for language in languages] print(uppercase) 

Output:

['PYTHON', 'JAVASCRIPT', 'PHP'] 

Another example:

names = ["Anjali", "Alex", "Sam", "Michael"] short_names = [name for name in names if len(name) <= 4] print(short_names) 

Output:

['Alex', 'Sam'] 

Using range()

You can create lists directly from range().

squares = [x ** 2 for x in range(1, 6)] print(squares) 

Output:

[1, 4, 9, 16, 25] 

This can be useful when generating predictable sequences.

Nested List Comprehensions

List comprehensions can also contain multiple loops.

For example:

matrix = [ [1, 2], [3, 4] ] flattened = [ number for row in matrix for number in row ] print(flattened) 

Output:

[1, 2, 3, 4] 

This is powerful, but it's also where list comprehensions can become harder to understand.

If a comprehension starts looking complicated, a regular loop may be the better choice.

When Should You Use List Comprehension?

List comprehensions work well when the operation is simple and easy to understand.

Good:

squares = [x ** 2 for x in numbers] 

Good:

evens = [x for x in numbers if x % 2 == 0] 

But imagine trying to squeeze several conditions and transformations into one line.

Technically valid Python isn't always readable Python.

For complex logic, prefer:

result = [] for item in items: # multiple steps  # conditions  # calculations  result.append(value) 

Readable code is more valuable than clever code.

List Comprehension vs map() and filter()

Python also provides map() and filter().

For example:

numbers = [1, 2, 3, 4] doubled = list(map(lambda x: x * 2, numbers)) 

The list comprehension equivalent is:

doubled = [x * 2 for x in numbers] 

For filtering:

evens = list(filter(lambda x: x % 2 == 0, numbers)) 

Equivalent comprehension:

evens = [x for x in numbers if x % 2 == 0] 

Neither approach is universally better.

But for many straightforward transformations and filters, comprehensions can be easier to read.

Common Beginner Mistakes

1. Forgetting the for

Incorrect:

[x * 2 x in numbers] 

Correct:

[x * 2 for x in numbers] 

2. Putting a Filtering Condition in the Wrong Place

Correct filtering syntax:

[x for x in numbers if x > 5] 

3. Making the Comprehension Too Complex

If you need several nested conditions and transformations, don't force everything into one expression.

Use a regular loop.

Your future self—and anyone reviewing your code—will thank you.

Quick Challenge

What will this code print?

numbers = [1, 2, 3, 4, 5] result = [ x * 2 for x in numbers if x % 2 != 0 ] print(result) 

Can you work it out before running the code?

The answer is:

[2, 6, 10] 

Only the odd values 1, 3, and 5 pass the condition, and each is then multiplied by 2.

Quick Recap

List comprehension:

[expression for item in iterable] 

With filtering:

[expression for item in iterable if condition] 

With if-else:

[value_if_true if condition else value_if_false for item in iterable] 

The main idea is simple:

Transform → Iterate → Optionally Filter

Once this pattern becomes familiar, you'll start noticing many places where a long loop can be expressed more clearly.

Watch the Video Tutorial

I've also explained Python List Comprehension step by step in Hinglish on my YouTube channel, Anjali Gupta Techverse.

🎥 Add your Lesson 20 YouTube URL here.

If you're learning Python from the beginning, you can follow the complete Python series lesson by lesson.

What's Next?

After list comprehensions, you can explore:

  • Dictionary Comprehension
  • Set Comprehension
  • Exception Handling
  • More practical Python projects

I'll continue covering these topics in the upcoming tutorials.

If this guide helped you, feel free to leave a comment.

What do you prefer for simple transformations: a traditional for loop or list comprehension?

Happy coding! 🐍