Python List Comprehension with If Else

Recently, I was working on a project where I needed to process a list of student scores and classify them as Pass or Fail based on their marks. The challenge was to do this efficiently without writing multiple lines of code.

That’s when I turned to Python list comprehension with if-else. It’s one of those Python features that not only makes your code cleaner but also much faster to write and execute.

In this tutorial, I’ll show you how to use if-else in Python list comprehension with simple, real-world examples. I’ll also share a few tricks.

What is List Comprehension in Python?

Before we add conditions, it’s important to understand what list comprehension is. List comprehension in Python is a concise way to create lists by applying an expression to each item in an iterable (like a list, tuple, or range).

Normally, we might use a for loop to create a new list. But with list comprehension, we can do it in just one line.

Here’s a basic example:

numbers = [1, 2, 3, 4, 5]
squares = []
for num in numbers:
    squares.append(num ** 2)
print(squares)  # Output: [1, 4, 9, 16, 25]

# Using Python list comprehension
squares_comp = [num ** 2 for num in numbers]
print(squares_comp)  # Output: [1, 4, 9, 16, 25]

As you can see, both methods give the same result, but the second one is much cleaner and more readable.

Add an If Condition in Python List Comprehension

Sometimes, you only want to include certain elements in your new list. For example, let’s say you want to extract only even numbers from a list.

Here’s how you can do it using a conditional if inside a list comprehension.

numbers = [10, 15, 20, 25, 30, 35, 40]

# Using if condition in list comprehension
even_numbers = [num for num in numbers if num % 2 == 0]

print(even_numbers)  # Output: [10, 20, 30, 40]

You can see the output in the screenshot below.

python list comprehension if else

This is extremely useful when filtering data, something I often do when cleaning large datasets in Python.

Python List Comprehension with If-Else

Now, let’s take it one step further. What if you want to apply a different expression based on a condition?

That’s where if-else in list comprehension comes in handy.

Here’s a simple example:

numbers = [10, 15, 20, 25, 30]

# Using if-else in Python list comprehension
result = ["Even" if num % 2 == 0 else "Odd" for num in numbers]

print(result)  # Output: ['Even', 'Odd', 'Even', 'Odd', 'Even']

You can see the output in the screenshot below.

python list comprehension if

In this example, Python checks each number. If it’s even, it adds “Even” to the list; otherwise, it adds “Odd”.

Real-World Example: Classify Student Grades

Let’s make it more practical. Suppose you have a list of student scores, and you want to label each student as Pass or Fail based on a passing mark of 60.

Here’s how you can do it easily using Python list comprehension with if-else.

scores = [85, 42, 77, 59, 90, 61, 48]

# Classify scores as Pass or Fail
status = ["Pass" if score >= 60 else "Fail" for score in scores]

print(status)  # Output: ['Pass', 'Fail', 'Pass', 'Fail', 'Pass', 'Pass', 'Fail']

This one-liner is not only elegant but also very efficient for large datasets. I often use this approach when processing exam or survey data in my Python projects.

Use If Else with Multiple Conditions

Sometimes, you may want to handle more than two conditions. For example, let’s categorize temperatures in different U.S. cities as Cold, Warm, or Hot.

temperatures = [35, 68, 85, 95, 55, 72]

# Categorize temperature levels
weather = [
    "Cold" if temp < 60 else
    "Warm" if temp < 85 else
    "Hot"
    for temp in temperatures
]

print(weather)  # Output: ['Cold', 'Warm', 'Warm', 'Hot', 'Cold', 'Warm']

You can see the output in the screenshot below.

list comprehension if else

This nested if-else structure works perfectly inside Python list comprehension. It’s great for quick data classification tasks.

Python List Comprehension with If-Else and Function Calls

You can also call functions inside list comprehensions. This helps when you want to perform a more complex operation.

Let’s say we want to round numbers differently based on whether they are above or below 50.

def adjust_value(num):
    return round(num / 10) * 10

values = [23, 47, 52, 68, 91, 45]

# Apply function conditionally
adjusted = [adjust_value(num) if num >= 50 else num for num in values]

print(adjusted)  # Output: [23, 47, 50, 70, 90, 45]

This technique is useful in data transformation pipelines, especially in financial or statistical Python applications.

Use If Else with Strings in Python List Comprehension

Let’s look at another real-world example, processing customer feedback. Suppose you have a list of reviews, and you want to label them as Positive or Negative based on certain keywords.

reviews = ["Great product", "Not worth the price", "Excellent service", "Poor quality"]

# Label reviews
labels = [
    "Positive" if "Great" in review or "Excellent" in review else "Negative"
    for review in reviews
]

print(labels)  # Output: ['Positive', 'Negative', 'Positive', 'Negative']

You can see the output in the screenshot below.

list comprehension

This approach is simple but effective for quick text classification tasks in Python.

Use If Else with Dictionaries in List Comprehension

You can also use list comprehension with dictionaries. For instance, let’s say you have a dictionary of employee names and their working hours, and you want to identify who worked overtime.

employees = {"John": 38, "Sarah": 42, "Mike": 45, "Emma": 36}

# Identify overtime employees
overtime = [
    f"{name}: Overtime" if hours > 40 else f"{name}: Regular"
    for name, hours in employees.items()
]

print(overtime)
# Output: ['John: Regular', 'Sarah: Overtime', 'Mike: Overtime', 'Emma: Regular']

This is one of my favorite use cases; it’s clean, readable, and perfect for quick reporting tasks.

Python List Comprehension with If-Else and Nested Lists

Sometimes, you may need to flatten or transform nested lists conditionally. Let’s say you have a list of lists representing sales data, and you want to replace missing values (None) with 0.

sales = [[100, None, 250], [None, 300, 150], [400, None, None]]

# Replace None with 0
cleaned_sales = [
    [0 if val is None else val for val in sublist]
    for sublist in sales
]

print(cleaned_sales)
# Output: [[100, 0, 250], [0, 300, 150], [400, 0, 0]]

This is a common pattern when cleaning real-world data in Python, especially when working with CSV or Excel files.

When Not to Use If-Else in List Comprehension

While Python list comprehension is powerful, it’s not always the best choice. If your logic becomes too complex or spans multiple lines, it’s better to use a regular expression for loop for readability.

Here’s a quick rule I follow:

If your list comprehension takes more than one screen line, rewrite it as a loop.

Readability always comes first in Python.

Conclusion

Python list comprehension with if-else is one of those features that can make your code elegant, concise, and efficient. It’s perfect for filtering, transforming, and classifying data, whether you’re analyzing student grades, temperatures, or sales reports.

Over the years, I’ve found that mastering list comprehension not only improves performance but also helps write more Pythonic code. Once you start using it, you’ll find yourself replacing many traditional loops with clean one-liners.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.