Python Arena
Step 3 of 4

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:

In the Python interpreter
>>> 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)
Output
['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)
Output
[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 if at 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 if with an else, before the for, is part of the expression. It decides what each item becomes, and the new list has as many items as the original.
In the Python interpreter
>>> 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]
Python stops with
  File "main.py", line 2
    fixed = [n for n in numbers if n > 0 else 0]
                                         ^^^^
SyntaxError: invalid syntax

Python points at the else: where it is, it makes no sense. Move the whole n if n > 0 else 0 to the front.

Your task

Challenge 1 of 3

Fill in the blank with the condition, so that every negative reading becomes 0 and the others stay as they are. The program should print:

[12, 0, 7, 0, 0, 5]

Challenge 2

What does this program print? Type each line it prints.

Challenge 3

A chat program hides words that aren't allowed. Write a function censor(words, banned) that returns a new list where every word that is in the list banned is replaced with "***", and the other words stay as they are. Use a list comprehension.

For example, this call:

print(censor(["you", "silly", "goose"], ["silly", "dumb"]))

prints:

['you', '***', 'goose']