Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Count frequencies of all elements in array in Python using collections module
Python lists allow duplicate elements, so we often need to count how many times each element appears. The frequency of elements indicates how many times an element occurs in a list. The Counter class from the collections module provides an efficient way to count element frequencies.
Syntax
Counter(iterable)
Where iterable is any Python iterable like a list, tuple, or string.
Basic Example
The Counter() function returns a dictionary-like object with elements as keys and their counts as values −
from collections import Counter
days = ['Mon', 'Tue', 'Wed', 'Mon', 'Mon', 'Tue']
# Finding count of each element
day_freq = Counter(days)
# Printing result of counter
print(day_freq)
# Printing it using loop
for key, value in day_freq.items():
print(key, "has count", value)
Counter({'Mon': 3, 'Tue': 2, 'Wed': 1})
Mon has count 3
Tue has count 2
Wed has count 1
Counting Numbers in a List
Counter works with any type of elements, including numbers −
from collections import Counter
numbers = [1, 2, 3, 1, 2, 1, 4, 5, 4]
num_freq = Counter(numbers)
print("Number frequencies:")
print(num_freq)
Number frequencies:
Counter({1: 3, 2: 2, 4: 2, 3: 1, 5: 1})
Most Common Elements
Counter provides the most_common() method to get the most frequent elements −
from collections import Counter
letters = ['a', 'b', 'c', 'a', 'b', 'a', 'd']
letter_freq = Counter(letters)
# Get all elements sorted by frequency
print("All elements by frequency:")
print(letter_freq.most_common())
# Get top 2 most common elements
print("\nTop 2 most common:")
print(letter_freq.most_common(2))
All elements by frequency:
[('a', 3), ('b', 2), ('c', 1), ('d', 1)]
Top 2 most common:
[('a', 3), ('b', 2)]
Counting Characters in a String
Counter can also count characters in a string −
from collections import Counter
text = "hello world"
char_freq = Counter(text)
print("Character frequencies:")
for char, count in char_freq.items():
if char != ' ': # Skip space for cleaner output
print(f"'{char}': {count}")
Character frequencies: 'h': 1 'e': 1 'l': 3 'o': 2 'w': 1 'r': 1 'd': 1
Key Methods
| Method | Description | Example |
|---|---|---|
most_common(n) |
Returns n most common elements | counter.most_common(3) |
elements() |
Returns iterator over elements | list(counter.elements()) |
total() |
Sum of all counts | counter.total() |
Conclusion
The Counter class from the collections module provides an efficient way to count element frequencies in Python. Use most_common() to get the most frequent elements and items() to iterate through all counts.
