What is counter ?
Counter is a container included in the collections module.
What is Container ?
Containers are objects that hold objects. They provide a way to access the contained objects and iterate over them. Examples of built in containers are Tuple, list and dictionary. Others are included in Collections module.
A Counter is a subclass of dict. Therefore it is an unordered collection where elements and their respective count are stored as dictionary. This is equivalent to bag or multiset of other languages.
Syntax :
class collections.Counter([iterable-or-mapping])
Initialization :
The constructor of counter can be called in any one of the following ways :
Example of each type of initialization :
python - Sample - python code :
Output of all the three lines is same :
Counter({'B': 5, 'A': 3, 'C': 2}) Counter({'B': 5, 'A': 3, 'C': 2}) Counter({'B': 5, 'A': 3, 'C': 2})
Updation :
We can also create an empty counter in the following manner :
coun = collections.Counter()
And can be updated via update() method .Syntax for the same :
coun.update(Data)
python - Sample - python code :
python tutorial - Output :
Counter({1: 4, 2: 3, 3: 1}) Counter({1: 5, 2: 4, 3: 1, 4: 1})
- Data can be provided in any of the three ways as mentioned in initialization and the counter’s data will be increased not replaced.
- Counts can be zero and negative also.
python - Sample - python code :
python tutorial - Output :
Counter({'c': 6, 'B': 0, 'A': -6})
python - Sample - python code :
python tutorial - Output :
Counter({'blue': 3, 'red': 2, 'yellow': 1})