Comprehensions with conditions
Python · Unit 15: Comprehensions and generators
- Full plan
- Python
- 10 exercises
An if at the end of a comprehension filters: only the items that match go in.
You already used it with lists, and it works the same with sets and dictionaries.
ages = [12, 20, 17, 30]
adult = {a for a in ages if a >= 18}
print(sorted(adult))Prints
[20, 30]
The rest of the explanation is in the lesson, which is part of the full plan.
Exercises in this lesson
You do them in the app, which checks them on the spot and explains why.
1. Predict the output
This dictionary holds the price of each product. What does it print?
2. Complete the code
Fill in the blank to keep only the people who are of age.
3. Predict the output
What does this code print?
4. Predict the output
These are three marks; 6 is the lowest passing one. What does it print?
5. Multiple choice
How are
[n for n in nums if n > 0]and[n if n > 0 else 0 for n in nums]different?6. Find the bug
It should print a 1 for each passing mark and a 0 for each failing one. Which line has the error?
7. Find the case that fails
max_even(ns)should return the largest even number in the list, and 0 if there is none. Which call breaks it?8. Multiple choice
Which of these jobs is better written with a plain
forthan with a comprehension?9. Put the lines in order
Put the lines in order to print how many marks passed and how many points they add up to.
10. Predict the output
These are the movements in an account. What does it print?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.