DEV Community

Cover image for Python collections, Part -I

Posted on

Python collections, Part -I

Python always surprises and this time it made my work a lot easier so I am writing this

Python collections are container datatypes.So, what are they?Container datatypes are data structures that store other objects(integers,string,list user-defined objects) and also provide a way to access and traverse them.

Python provides some of these container datatypes in collections module to make it easier to store and access items.In this first part we will see counter.
It returns a dictionary with the keys as the elements of the object with the count of the element as the value.
Let's see an example:

>>> from collections import Counter
>>> c = Counter("ABCDABC")
>>> c #returns the count of each letter in string
Counter({'A': 2, 'B': 2, 'C': 2, 'D': 1})

Enter fullscreen mode Exit fullscreen mode
>>> from collections import Counter
>>> c = Counter(['python','collections','are','interesting'])
>>> c #returns the counts of each element in list
Counter({'python': 1, 'collections': 1, 'are': 1, 'interesting': 1})

Enter fullscreen mode Exit fullscreen mode

Getting values from counter:

>>> c['collections']
1 #collecctions appeared only once
>>> c['interesting']
1 #intersting appeared only  once  
>>> c['movie']
0 # 'movie' is not present so the output is 0
Enter fullscreen mode Exit fullscreen mode

Note: Trying to get values not present in counter return 0.
For more
Python documentation
Thanks and merry Christmas

Top comments (0)