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
- For each
n,"even" if n % 2 == 0 else "odd"gives"even"or"odd", and that value goes into the list. - Every item gets a value. Nothing is removed, so 8 numbers give 8 labels.
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]
clippedhas 5 items: each negative number (and 0) is replaced by 0.kepthas 2 items: the other numbers are dropped.- An
ifafter theforcannot have anelse. Writing[n for n in nums if n > 0 else 0]is aSyntaxError.
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.