Counter Collection in Python

Level 4163 keystrokes

This uses Counter to count occurrences of elements. most_common() returns elements and counts in descending order.

Python code

# Import Counter from collections module
1from collections import Counter
2
# Create a list with repeated words
3words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
# Counter counts occurrences of each element
4count = Counter(words)
5
# Print the Counter object showing all counts
6print(count)
# Get the 2 most common elements with their counts
7print(count.most_common(2))

Output

Counter({'apple': 3, 'banana': 2, 'cherry': 1})
[('apple', 3), ('banana', 2)]
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • "× 12
  • ,× 5
  • (× 4
  • )× 4
  • =× 2
  • _× 1
  • .× 1
  • [× 1
  • ]× 1

More Python examples at level 4

← Python typing practice