PythonMastery

if else in a list comprehension in Python

Use if else inside a list comprehension to choose a value for every item, such as odd or even labels. Why it goes before for, but a filter goes after.

A conditional expression (a if condition else b) gives back one of two values. Inside a list comprehension, it chooses a value for every item, so the new list has the same length as the old one.

The program

python
nums = range(1, 9)

labels = ["even" if n % 2 == 0 else "odd" for n in nums]
print(labels)
output
['odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even']

How it works

Where the if goes

The position of if changes what it does:

python
nums = [5, -3, 0, 8, -1]

# if ... else BEFORE for: choose a value for every item
clipped = [n if n > 0 else 0 for n in nums]
print(clipped)

# if AFTER for: keep only some items (a filter)
kept = [n for n in nums if n > 0]
print(kept)
output
[5, 0, 0, 8, 0]
[5, 8]

You can use both in one comprehension. This keeps only the numbers that are not 0, then labels each one:

python
nums = [5, -3, 0, 8, -1]

signs = ["+" if n > 0 else "-" for n in nums if n != 0]
print(signs)
output
['+', '-', '+', '-']

Related programs: List comprehension with if condition.

Learn the idea: Comprehensions: Lists, Dicts, Sets, Generators, Control Flow: Conditionals