The Counter
class, available in the collections
module, is used to count the frequency of elements in a collection. It returns a dictionary-like object where the elements are keys and their counts are values.
To use the Counter
class, you need to import it from the collections
module:
from collections import Counter
Let's explore some practical examples of using the Counter
class:
Example 1: Counting Elements in a List:
fruits = ["apple", "banana", "orange", "apple", "banana", "apple"] fruit_counter = Counter(fruits) print(fruit_counter) # Output: Counter({'apple': 3, 'banana': 2, 'orange': 1}) print(fruit_counter["apple"]) # Output: 3 print(fruit_counter["banana"]) # Output: 2
In this code, we create a Counter
object called fruit_counter
from a list of fruits. The Counter
object counts the frequency of each fruit. We can access the count of a specific fruit by indexing the fruit_counter
object with the fruit name.
Example 2: Counting Characters in a String:
text = "Hello, world!" char_counter = Counter(text) print(char_counter) # Output: Counter({'l': 3, 'o': 2, 'H': 1, 'e': 1, ',': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1, '!': 1}) print(char_counter["l"]) # Output: 3 print(char_counter["o"]) # Output: 2
In this code, we create a Counter
object called char_counter
from a string. The Counter
object counts the frequency of each character in the string. We can access the count of a specific character by indexing the char_counter
object with the character.