What is a container?
Containers — these are objects that contain objects. They provide a way to access and iterate over contained objects. Examples of built-in containers are Tuple, List, and Dictionary. Others are included in the Collections module.
Counter — it is a subclass of dict. Hence, it is an unordered collection in which the elements and their corresponding values are stored as a dictionary. This is equivalent to a bag or a multitude of other languages.
Syntax:
.Counter class collections ([iterable-or-mapping])
Initialization:
The counter constructor can be called in any of the following ways:
An example of each type of initialization:
|
The output of all three lines is the same:
Counter ({’B’: 5,’ A’: 3, ’C ’: 2}) Counter ({’ B’: 5, ’A’: 3,’ C’: 2}) Counter ({’B’: 5,’ A’: 3, ’C’: 2})
Update:
We can also create an empty counter like this:
coun = collections.Counter ()
And we can It can be updated via the update () method. Syntax for the same:
coun.update (Data)
|
Output:
Counter ({1: 4, 2: 3, 3: 1}) Counter ({1: 5, 2: 4, 3: 1, 4: 1})
- Data can be provided in any of three ways, as indicated in the initialization, and the counter data will be incremented, not replaced.
- The score can be either zero or negative.
# Python program to demonstrate what counts
< br /># Counter can be 0 or negative
from
collections
import
Counter
c1
=
Counter (A
=
4
, B
=
3
, C
=
10
)
c2
=
Counter (A
=
10
, B
=
3
, C
=
4
)
c1.subtract (c2)
print
(c1)
Exit:
Counter ({’c’: 6,’ B’: 0, ’A’: -6})
- We can use Counter to count individual list items or other collections.
# An example program where different elements of the list
# counted using counter
from
collections
import
Counter
# Create list
z
=
[
’ blue’
,
’red’
,
’blue’
,
’ yellow’
,
’blue’
,
’ red’
]
# Count individual items and print counter
print
(Counter (z))
Output:
Counter ({’blue’: 3,’ red’: 2 , ’yellow’: 1})
This article is updated by Mayank Rawat If you love Python.Engineering and would like to contribute, you can also write article using contribute.python.engineering or by mailing article [email protected] See my article appearing on the Python.Engineering homepage and help other geeks.
Please post comments if you find anything wrong or if you would like to share more information on the topic discussed above.