How to initialize a Python counter?
To use Counter, you need to import it first:
How to use Python Counter?
A Counter is a dictionary where objects are stored as keys and are considered values. You can provide a sequence or iteration of hashable objects as an argument to the class constructor for counting counter. Counter internally iterates through the input sequence, counts how many times a given object is encountered, and stores the objects as keys and counters as values. If you want to count multiple objects simultaneously, you need to use sequence or iteration to initialize the counter.
Python Counter Examples
The following examples demonstrate how Counter works in Python with a detailed description:
Counter with Python String
In the example below, a string is passed to Counter. It returns a dictionary with key/value pairs, where the key is the element and the value is the count. Whitespace is also treated as an element by the Counter.
Counter with Python List
In the example below, a list is passed to Counter. This Counter will convert the elements in the list passed to it into hash table objects where the elements will become keys, and the values will be the number of elements in the list. Once you pass the list to Counter, it will provide you with the count of each element in the list.
Counter with Python Dictionary
The following example passes a dictionary to Counter. Dictionaries contain pairs of keys and values. Once the dictionary has been passed to the Counter, the elements will become the keys and the values will be the number of elements in the dictionary.
Counter with Python Tuple
Below is an example of how a Tuple is passed to a Counter. A tuple is a collection of objects separated by commas. Once a tuple has been given to a counter, it will be converted to a hash table object where the elements will become the keys and the values the number of elements from the tuple.
Why use Python Counter?
The main reasons for using Python 3 Counter:
- The counter stores data in an unordered collection like hash table objects. Items here represent keys and counter as values.
- The counter can efficiently perform arithmetic operations such as addition, subtraction, intersection, and union.
- The counter allows you to count the items in a repeating list.
- The counter can also count items from another counter.