CodeBlanks Logo Icon CodeBlanks

Counter

Learn counting with Counter.

Counter

Counter is a dictionary type from the collections module that counts how many of each item there is. It quickly gives the count of items in a list, string or any iterable.

Example: Counter("apple") produces {'p': 2, 'a': 1, 'l': 1, 'e': 1}. Writing c["p"] returns 2. With c.most_common(2) you can get the two most frequent items. Counter is very useful for word frequency or vote counting.

The most_common method

most_common(n) returns the n most frequent items as a list of (item, count) tuples. Counts are in decreasing order; the most frequent item is first.

Example: Counter([1, 1, 2, 3, 1]).most_common(2) returns [(1, 3), (2, 1)]. So 1 appeared three times, 2 once. If n is not given, all items are returned as a sorted list. This method is ideal for finding the most frequent values quickly.

Practice Count letters with Counter

Start with from collections import Counter. Create a Counter with c = Counter("apple") and print the count of p with print(c["p"]).

Starter code

main.py
# Count letters with Counter

Sample solution

main.py
# Count letters with Counter
from collections import Counter

c = Counter("apple")
print(c["p"])

Expected output

2

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which module does Counter come from?

  • functools
  • collections Correct answer
  • itertools
  • typing

Explanation: Counter is in the collections module.

2 Counter import line

Question
from collections import ____

c = Counter("apple")
print(c["p"])
Answer
from collections import Counter

c = Counter("apple")
print(c["p"])

Explanation: Counter is imported from the collections module.

3 Match the Counter parts

Term Meaning
Counter Counting dict
c["p"] Item count
most_common Most frequent
collections Module

All lessons in Intermediate