collections
Python · Unit 16: The standard library
- Full plan
- Python
- 11 exercises
Back in unit 7 you counted with d[x] = d.get(x, 0) + 1. Counter does that for you: hand it a string or a list and it tells you how many times each thing shows up.
It comes from the collections module, the toolbox of data structures.
from collections import Counter
c = Counter("hello")
print(c)Prints
Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1})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
What does this code print?
2. Complete the code
Complete it to count the votes. It should print: 2
3. Predict the output
What does this code print?
4. Predict the output
What does this code print?
5. Find the bug
It should print how many times the most repeated letter shows up, that is 3. Which line has the error?
6. Multiple choice
You have
c = Counter("hello"). What happens withc["z"]?7. Predict the output
What does this code print?
8. Predict the output
What does this code print?
9. Complete the code
Complete it to group the names by their first letter.
10. Put the lines in order
Put the lines in order to build
top_letter(text), which returns the most repeated letter.11. Find the case that fails
top_letter(text)returns the most repeated letter, or "-" if the text is empty. Which call breaks it?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.