Filtering with if
🌍 In real life. At a mango market, a sorter looks at each mango and puts only the ripe ones in the box; the rest stay behind. Sometimes the sorter also does something to each mango that passes, like putting a sticker on it.
A comprehension can sort like that too, with an if at the end.
The idea in one sentence: [expression for name in source if condition] keeps only the items whose condition is True, then makes the expression from each one.
Its words:
- filter: the
if conditionat the end, which decides whether an item goes in - transform: the expression at the front, which decides what goes in
a if condition else bat the front: changes every item one of two ways, skipping none
Step by step, for [n for n in range(1, 7) if n % 2 == 0]:
- n is 1:
1 % 2 == 0is False, so 1 is skipped. - n is 2: True, so 2 goes in. And so on for 3 to 6.
- The result is
[2, 4, 6].
evens = [n for n in range(1, 7) if n % 2 == 0]
print(evens)
words = ["hi", "apple", "fig", "melon"]
print([w for w in words if len(w) > 3])The condition and the expression work together: first the if decides whether an item goes in, then the expression decides what goes in.
To change every item one of two ways (instead of skipping some), put the one-line a if condition else b from Lesson 6.4 in the expression, at the front:
print(["even" if n % 2 == 0 else "odd" for n in range(1, 5)])Why two places for if? They do different jobs. An if at the end is a gate: some items don't get through, so the new list can be shorter. An if ... else at the front is a choice of value: every item gets through, changed one way or the other, so the new list has the same length.
Mistakes and edge cases.
- else on the filter.
[n for n in range(5) if n % 2 == 0 else 0]givesSyntaxError: invalid syntax. To keep every item, move the choice to the front:[n if n % 2 == 0 else 0 for n in range(5)]. - if without else at the front.
[x if x > 0 for x in nums]givesSyntaxError: expected 'else' after 'if' expression. A filter goes at the end. - An empty result. If no item passes, you get
[], with no error; check before takingmax()of it.
Quiz
What does this print?
print([n for n in range(6) if n % 3 == 0])What does this print?
print([w for w in ["a", "abc", "ab"] if len(w) >= 2])What does this print?
print(["big" if x > 2 else "small" for x in [1, 3]])Where does an
ifthat filters (skips items) go?- At the end, after the for part
- At the front, before for
- On its own line
Which line has a mistake?
nums = [3, -1, 2] pos = [x for x in nums if x > 0 else 0] print(pos)
Coding tasks
Ask for whole numbers on one line. Print a list of only the positive ones (greater than 0), in order.
Ask for how many candies each kid has (on one line), then for a number of extra candies. For each kid, print whether giving them all the extra candies would make them have the most (at least as many as anyone). Print the list of True/False.
Ask for some words on one line. Print a list of the words longer than 3 letters, in capitals.