Collection

collections is a built-in module in python and it is type of container that contains different module like Counter,deque,UserDict,UserList etc and some built-in container are List,tuple,Dictonary.

Syntax

import collections from Module_name

Counter

Counter is function comes in the collections module and it is subclass of dictionary object and the use of Counter function count the number of element and return in the form of unordered Dictonary,here the key specifies the element of sequence and value represents the number of element of that sequence.

Syntax

from collections import Counter
dict_var=Counter(sequence)
#---------or--------------
import collections
var_dict=collections.Counter(sequence)

Example

import collections
sequence=['a','b','a','b','a','b','a','b']
var_dict=collections.Counter(sequence)
print(var_dict)

Output

 Counter({'a': 4, 'b': 4})

Example with from

from collections import Counter
sequence=['a','b','a','b','a','b','a','b']
var_dict=Counter(sequence)
print(var_dict)

Output

Counter({'a': 4, 'b': 4})

Accessing the keys and values of dictionary

We can access the keys and values of the unordered dictonary.

from collections import Counter
sequence=['a','b','a','b','a','b','a','b']
var_dict=Counter(sequence)
print("Keys:",var_dict.keys())
print("values:",var_dict['a'])

Output

Keys: dict_keys(['a', 'b'])
values: 4

elements() function

elements() function return the list which contains list of all the elements in the Counter object.

from collections import Counter
sequence=['a','b','a','b','a','b','a','b']
var_dict=Counter(sequence)
print("Element are:",list(var_dict.elements()))

Output

Element are: ['a', 'a', 'a', 'a', 'b', 'b', 'b', 'b']