![]() |
VOOZH | about |
Counter is a subclass of Python’s dict from the collections module. It is mainly used to count the frequency of elements in an iterable (like lists, strings or tuples) or from a mapping (dictionary). It provides a clean and efficient way to tally items without writing extra loops and comes with helpful built-in methods.
Counter({1: 3, 3: 2, 2: 1, 4: 1})
Explanation: Counter object shows that 1 appears 3 times, 3 appears 2 times, 2 appears once and 4 appears once.
collections.Counter([iterable-or-mapping])
Parameters (all optional):
Return Type: Returns a collections.Counter object (dictionary-like).
We can create Counters from different data sources.
Counter({3: 3, 2: 2, 1: 1})
Counter({2: 3, 1: 2, 3: 1})
Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1})
Explanation:
Refer to collection module to learn in detail.
We can access the count of each element using the element as the key. If an element is not in the Counter, it returns 0.
1 2 3 0
Explanation: Counter returns the count of each element. If an element does not exist (4 in this case), it returns 0.
Counter and dictionary are similar, but Counter provides additional functionality specifically for counting elements.
1. update(): Adds counts from another iterable or mapping. Existing counts increase and new elements are added.
Counter({2: 3, 1: 2, 3: 2})
Explanation:
2. elements(): Returns an iterator over elements repeating each as many times as its count. Elements are returned in arbitrary order.
[1, 1, 2, 2, 2, 3]
Explanation:
3. most_common(): Returns a list of the n most common elements and their counts from the most common to the least. If n is not specified, it returns all elements in the Counter.
[(3, 4), (2, 3)]
Explanation:
4. Increasing Count Manually: Increases the count of a single element by 1.
Counter({2: 3, 1: 2, 3: 1, 4: 1})
Explanation:
5. subtract(): Subtracts element counts from another iterable or mapping. Counts can go negative.
Counter({1: 2, 2: 1, 3: 0})
Explanation:
Note: Counts can even go negative if subtraction exceeds the original count.
Counters support addition, subtraction, intersection and union operations, allowing for various arithmetic operations.
Counter({2: 3, 3: 3, 1: 1, 4: 1})
Counter({1: 1, 2: 1})
Counter({2: 1, 3: 1})
Counter({2: 2, 3: 2, 1: 1, 4: 1})