Choosing a value with if and else
In part 7 you met the conditional expression, an if and else on one line that gives one of two values:
>>> age = 15
>>> "adult" if age >= 18 else "minor"
'minor'It reads like a sentence: the value is "adult" if the condition is true, else it's "minor".
A conditional expression can be the expression of a list comprehension. Then it chooses a value for each item separately, and every item gets into the new list in one form or the other:
scores = [72, 45, 90, 38]
results = ["pass" if score >= 50 else "fail" for score in scores]
print(results)
['pass', 'fail', 'pass', 'fail']The shape is:
[value1 if condition else value2 for item in series]
Either value can use the item. Here negative readings from a broken sensor are replaced with zero, and the other readings are kept as they are:
readings = [12, -3, 7, -1, 5]
cleaned = [r if r >= 0 else 0 for r in readings]
print(cleaned)
[12, 0, 7, 0, 5]Two different ifs
There are now two places for an if in a comprehension, and they do different jobs:
- An
ifat the end, after the series, is a filter. It decides which items get into the new list at all, so the list can get shorter. - An
ifwith anelse, before thefor, is part of the expression. It decides what each item becomes, and the new list has as many items as the original.
>>> numbers = [4, -2, 9, -5]
>>> [n for n in numbers if n > 0]
[4, 9]
>>> [n if n > 0 else 0 for n in numbers]
[4, 0, 9, 0]If you put the else at the end, Python can't read it. A filter has no else: an item either passes or it doesn't.
numbers = [4, -2, 9, -5]
fixed = [n for n in numbers if n > 0 else 0]
File "main.py", line 2
fixed = [n for n in numbers if n > 0 else 0]
^^^^
SyntaxError: invalid syntaxPython points at the else: where it is, it makes no sense. Move the whole n if n > 0 else 0 to the front.