DEV Community

Cover image for Python List Comprehension: Write Cleaner Code with Practical Examples
Anjali Gupta | Techverse
Anjali Gupta | Techverse

Posted on AI-assisted

Python List Comprehension: Write Cleaner Code with Practical Examples

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)
Enter fullscreen mode Exit fullscreen mode

Output:

[1, 4, 9, 16, 25]
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

For example:

numbers = [1, 2, 3, 4]

doubled = [x * 2 for x in numbers]

print(doubled)
Enter fullscreen mode Exit fullscreen mode

Output:

[2, 4, 6, 8]
Enter fullscreen mode Exit fullscreen mode

Let's break this down:

x * 2
Enter fullscreen mode Exit fullscreen mode

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

for x in numbers
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Using list comprehension:

squares = [x * x for x in numbers]
Enter fullscreen mode Exit fullscreen mode

Both approaches create the same result:

[1, 4, 9, 16, 25]
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output:

[2, 4, 6]
Enter fullscreen mode Exit fullscreen mode

The pattern becomes:

[expression for item in iterable if condition]
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output:

[4, 16, 36]
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output:

['Odd', 'Even', 'Odd', 'Even']
Enter fullscreen mode Exit fullscreen mode

Notice where the condition appears:

"Even" if condition else "Odd"
Enter fullscreen mode Exit fullscreen mode

comes before the for.

Compare these two patterns:

Filtering

[x for x in numbers if x > 5]
Enter fullscreen mode Exit fullscreen mode

Conditional transformation

["Even" if x % 2 == 0 else "Odd" for x in numbers]
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output:

['PYTHON', 'JAVASCRIPT', 'PHP']
Enter fullscreen mode Exit fullscreen mode

Another example:

names = ["Anjali", "Alex", "Sam", "Michael"]

short_names = [name for name in names if len(name) <= 4]

print(short_names)
Enter fullscreen mode Exit fullscreen mode

Output:

['Alex', 'Sam']
Enter fullscreen mode Exit fullscreen mode

Using range()

You can create lists directly from range().

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

print(squares)
Enter fullscreen mode Exit fullscreen mode

Output:

[1, 4, 9, 16, 25]
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output:

[1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

Good:

evens = [x for x in numbers if x % 2 == 0]
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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))
Enter fullscreen mode Exit fullscreen mode

The list comprehension equivalent is:

doubled = [x * 2 for x in numbers]
Enter fullscreen mode Exit fullscreen mode

For filtering:

evens = list(filter(lambda x: x % 2 == 0, numbers))
Enter fullscreen mode Exit fullscreen mode

Equivalent comprehension:

evens = [x for x in numbers if x % 2 == 0]
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

Correct:

[x * 2 for x in numbers]
Enter fullscreen mode Exit fullscreen mode

2. Putting a Filtering Condition in the Wrong Place

Correct filtering syntax:

[x for x in numbers if x > 5]
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Can you work it out before running the code?

The answer is:

[2, 6, 10]
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

With filtering:

[expression for item in iterable if condition]
Enter fullscreen mode Exit fullscreen mode

With if-else:

[value_if_true if condition else value_if_false for item in iterable]
Enter fullscreen mode Exit fullscreen mode

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! 🐍

Top comments (0)