Skip to the content

collections

Python · Unit 16: The standard library

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. 1. Predict the output

    What does this code print?

  2. 2. Complete the code

    Complete it to count the votes. It should print: 2

  3. 3. Predict the output

    What does this code print?

  4. 4. Predict the output

    What does this code print?

  5. 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. 6. Multiple choice

    You have c = Counter("hello"). What happens with c["z"]?

  7. 7. Predict the output

    What does this code print?

  8. 8. Predict the output

    What does this code print?

  9. 9. Complete the code

    Complete it to group the names by their first letter.

  10. 10. Put the lines in order

    Put the lines in order to build top_letter(text), which returns the most repeated letter.

  11. 11. Find the case that fails

    top_letter(text) returns the most repeated letter, or "-" if the text is empty. Which call breaks it?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →