0
0
Pythonprogramming~5 mins

List comprehension with if–else in Python

Choose your learning style9 modes available
Introduction

List comprehension with if-else lets you create a new list by choosing values based on a condition, all in one simple line.

You want to change numbers in a list to 'even' or 'odd' labels.
You need to replace negative numbers with zero but keep positives as they are.
You want to mark students as 'pass' or 'fail' based on their scores.
You want to create a list of prices with a discount applied only to expensive items.
Syntax
Python
new_list = [value_if_true if condition else value_if_false for item in original_list]

The if-else part goes before the for loop in the list comprehension.

This is different from a simple if filter, which comes after the for loop.

Examples
Labels each number as 'even' or 'odd'.
Python
numbers = [1, 2, 3, 4]
labels = ['even' if num % 2 == 0 else 'odd' for num in numbers]
print(labels)
Replaces negative temperatures with zero.
Python
temps = [-5, 3, 0, -1]
non_negative = [temp if temp >= 0 else 0 for temp in temps]
print(non_negative)
Marks scores as 'pass' or 'fail'.
Python
scores = [55, 70, 40]
results = ['pass' if score >= 50 else 'fail' for score in scores]
print(results)
Applies 10% discount only to prices over 100.
Python
prices = [100, 250, 50]
discounted = [price * 0.9 if price > 100 else price for price in prices]
print(discounted)
Sample Program

This program labels each number in the list as 'even' or 'odd' using list comprehension with if-else.

Python
def label_numbers(numbers):
    print(f"Original numbers: {numbers}")
    labeled = ['even' if number % 2 == 0 else 'odd' for number in numbers]
    print(f"Labeled numbers: {labeled}")

numbers_list = [10, 15, 22, 33, 40]
label_numbers(numbers_list)
OutputSuccess
Important Notes

Time complexity is O(n) because it processes each item once.

Space complexity is O(n) since it creates a new list of the same size.

A common mistake is putting the if-else after the for loop, which causes syntax errors.

Use this when you want to choose between two values for each item. Use a simple if filter if you want to include or exclude items.

Summary

List comprehension with if-else lets you pick one of two values for each item based on a condition.

The if-else goes before the for loop inside the brackets.

This makes your code shorter and easier to read when transforming lists.