Table of contents
1.
Introduction
2.
What is Collections Module?
3.
Counter
4.
OrderedDict
5.
Defaultdict
6.
ChainMap
7.
NamedTuple
8.
Deque
9.
UserDict
10.
UserList
11.
UserString
12.
Frequently Asked Questions
12.1.
What is Collections Module in Python?
12.2.
How many containers does the collections module in Python provide?
12.3.
How to set the default value of defaultdict in Python?The default value of the defaultdict can be set by defaultdict(lambda:x), where x is the default value. 
13.
Conclusion
Last Updated: Jun 26, 2024
Medium

Python Collections Module

Author Pallavi singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Every language provides a set of standard library packages which provide functionalities that helps programmers to write code without needing them to rewrite commonly used codes. This saves their time and closes the door for any error they may make while writing the basic code. 

Python Collections Module

Python also provides many standard libraries such as os, math, fun, functools, collections, etc. In this article, we will be discussing the Python collections module in complete detail.

What is Collections Module?

Python's collections module has a large number of specialised container data types that have been carefully built to solve certain programming challenges in a Pythonic and efficient manner. The module also provides Wrapper classes, making it safer to develop new classes that function similarly to the built-in types dict, list, and str.

Different types of containers are available in Python's collection module. 

A Container is a type of object that may be used to hold several objects and offer a mechanism to access and iterate over them. Tuple, List, Dictionary, and other built-in containers are some of the examples.

 

The containers provided by the collections module are

CounterOrderedDictDefaultDict
ChainMapNamedTupleDeque
UserdictUserListUserString

Read About, Divmod in Python, Fibonacci Series in Python

Counter

Counter is a sub-class of dict data type. It's used to maintain track of the items in an iterable in the form of an unordered dictionary, with the key representing the element and the value representing the count of that element in the iterable.

Syntax:

c = Counter(mapping/iterable)
You can also try this code with Online Python Compiler
Run Code

 

Example: 

from collections import Counter
c = Counter("aabbccdddeee")
print(c)
You can also try this code with Online Python Compiler
Run Code

Output:

Counter({'d': 3, 'e': 3, 'a': 2, 'b': 2, 'c': 2})
You can also try this code with Online Python Compiler
Run Code

 

Example: 

from collections import Counter
c = Counter([1,1,2,2,3])
print(c)
You can also try this code with Online Python Compiler
Run Code

Output:

Counter({1: 2, 2: 2, 3: 1})
You can also try this code with Online Python Compiler
Run Code

 

Example: 

from collections import Counter
c = Counter(a=5,b=9)
print(c)
You can also try this code with Online Python Compiler
Run Code

Output:

Counter({'b': 9, 'a': 5})
You can also try this code with Online Python Compiler
Run Code

 

Counter objects support the following methods:

  • elements(): it returns an iterator over elements repeating each as many times as its count.
  • most_common([x]): it returns a list of the x elements with the highest count. 

 

from collections import Counter
c = Counter([1,1,1,1,2,2,2,2,5,6,5,2,3,3,3,])
print(list(c.elements()))
print(c.most_common(2))
You can also try this code with Online Python Compiler
Run Code

 

Output:

[1, 1, 1, 1, 2, 2, 2, 2, 2, 5, 5, 6, 3, 3, 3]
[(2, 5), (1, 4)]
You can also try this code with Online Python Compiler
Run Code

 

You can practice by yourself with the help of online python compiler.

OrderedDict

A dictionary subclass called OrderedDict remembers the order in which keys were initially placed. Items are returned in the order their keys were initially added while iterating over an ordered dictionary. Because an ordered dictionary keeps track of its entry order, it may be used with sorting to produce a sorted dictionary.

If a key is removed and added again, the key is pushed to the last position to maintain the order. 

Example:

from collections import OrderedDict

ordDict = {}
ordDict[3]=4
ordDict[1]=2
ordDict[2]=3
ordDict[4]=1
print("Before")
for key in ordDict:
    print(key,ordDict[key])

ordDict.pop(3)
ordDict[3]=10
print("After")
for key in ordDict:
    print(key,ordDict[key])
You can also try this code with Online Python Compiler
Run Code

 

Output:

Before
3 4
1 2
2 3
4 1
After
1 2
2 3
4 1
3 10
You can also try this code with Online Python Compiler
Run Code

Defaultdict

It is a subclass of dictionary. It's used to supply default values for keys that don't exist, and it never throws a KeyError.

Example:

from collections import defaultdict
 
dic = defaultdict(lambda:0)
print(dic[1])
You can also try this code with Online Python Compiler
Run Code

Output:

0
You can also try this code with Online Python Compiler
Run Code

ChainMap

A ChainMap collects many dictionaries into a single unit and delivers a list of dictionaries.

Syntax:

collections.ChainMap(dictionary1, dictionary2)
You can also try this code with Online Python Compiler
Run Code

Example:

import collections
 
dic1 = {"a":1,"b":2}
dic2 = {"c":3,"d":4}
 
c = collections.ChainMap(dic1,dic2)
print(c)
print(c.keys())
print(c.values())
You can also try this code with Online Python Compiler
Run Code

 

Output:

ChainMap({'a': 1, 'b': 2}, {'c': 3, 'd': 4})
KeysView(ChainMap({'a': 1, 'b': 2}, {'c': 3, 'd': 4}))
ValuesView(ChainMap({'a': 1, 'b': 2}, {'c': 3, 'd': 4}))
You can also try this code with Online Python Compiler
Run Code

 

A new dictionary can be added to a chain map using the new_child method. It adds the new dictionary to the beginning of the chain of dictionaries. 

import collections
 
dic1 = {"a":1,"b":2}
dic2 = {"c":3,"d":4}
 
c = collections.ChainMap(dic1,dic2)
print(c)

dic3 = {"e":5,"f":6}
c1 = c.new_child(dic3)
print(c1)
You can also try this code with Online Python Compiler
Run Code

 

Output:

ChainMap({'a': 1, 'b': 2}, {'c': 3, 'd': 4})
ChainMap({'e': 5, 'f': 6}, {'a': 1, 'b': 2}, {'c': 3, 'd': 4})
You can also try this code with Online Python Compiler
Run Code

NamedTuple

The NamedTuple returns tuple-like objects with extra functionalities. In this, each position of the tuple can be named as well as indexed. 

Syntax:

collections.namedtuple(type_name,fields)
You can also try this code with Online Python Compiler
Run Code

 

For example, creating a namedtuple .

import collections
person = collections.namedtuple('person',["name","age","country"])
You can also try this code with Online Python Compiler
Run Code

 

Creating an object of person namedtupe. 

p1 = person("Apurv", 20, "India")
You can also try this code with Online Python Compiler
Run Code

 

Accessing the fields of p1.

print(p1.name)
print(p1.age)
print(p1.country)
You can also try this code with Online Python Compiler
Run Code

 

Output:

Apurv
20
India
You can also try this code with Online Python Compiler
Run Code

 

Example:

import collections
 
dic1 = {"a":1,"b":2}
dic2 = {"c":3,"d":4}
 
c = collections.ChainMap(dic1,dic2)
print(c)
print(c.keys())
print(c.values())
You can also try this code with Online Python Compiler
Run Code

 

Output:

Chain
You can also try this code with Online Python Compiler
Run Code

Deque

A deque, also called a Doubly-ended queue, is a specialized list that can perform append and pop operations from both sides of the list in constant time. 

Appending elements to the right in the deque is the same as the normal list. Appending elements and pop elements from the left can be done using deque.appendleft() and deque.popleft() method.  

Syntax:

collections.deque(list)
You can also try this code with Online Python Compiler
Run Code

 

Example:

import collections
 
l = [1,2,3,4,5]
d = collections.deque(l)
d.popleft()
print(d)
d.appendleft(9)
print(d)
You can also try this code with Online Python Compiler
Run Code

 

Output:

deque([2, 3, 4, 5])
deque([9, 2, 3, 4, 5])
You can also try this code with Online Python Compiler
Run Code

UserDict

UserDict is a string-like container that works as a wrapper over dict objects, similar to UserList and UserString. It's utilised when someone wants to make their own dict with some tweaks or other features.

 

Syntax:

collections.UserDict(dict)
You can also try this code with Online Python Compiler
Run Code

 

Example:

import collections
 
class CustomDict(collections.UserDict):
    def returnValueOfSmallestKey(self):
        keys = list(self.data.keys())
        return self.data[min(keys)]

List = CustomDict({1:"a",2:"b",3:"c"})
print(List)

print(List.returnValueOfSmallestKey())
You can also try this code with Online Python Compiler
Run Code

 

Output:

a
You can also try this code with Online Python Compiler
Run Code

UserList

UserList is a string-like container that works as a wrapper over list objects, similar to UserDict and UserString. It's utilised when someone wants to make their own list with some tweaks or other features.

 

Syntax:

collections.UserList(list)
You can also try this code with Online Python Compiler
Run Code

 

Example:

import collections
 
class CustomList(collections.UserList):
    def replaceMiddle(self,x):
        self.data[len(self.data)//2] = x

List = CustomList([1,2,3,4,5])
print(List)

List.replaceMiddle(9)
print(List)
You can also try this code with Online Python Compiler
Run Code

 

Output:

[1, 2, 3, 4, 5]
[1, 2, 9, 4, 5]
You can also try this code with Online Python Compiler
Run Code

UserString

UserString is a string-like container that works as a wrapper over string objects, similar to UserDict and UserList. It's utilised when someone wants to make their own strings with some tweaks or other features.

Syntax:

collections.UserString(string)
You can also try this code with Online Python Compiler
Run Code

 

Example:

import collections
 
class CustomString(collections.UserString):
    def replaceMiddle(self,x):
        temp = list(self.data)
        temp[len(temp)//2] = x
        self.data =  ''.join(temp)

string = CustomString("Thisisastring")
print(string)

string.replaceMiddle("x")
print(string)
You can also try this code with Online Python Compiler
Run Code

 

Output:

Thisisastring
Thisisxstring
You can also try this code with Online Python Compiler
Run Code

 

Frequently Asked Questions

What is Collections Module in Python?

Collections module in Python provides a large number of specialized containers that have been specially designed to solve specialized problems. 

How many containers does the collections module in Python provide?

The collections module provides the following containers: Counter, OrderedDict, DefaultDict, ChainMap, NamedTuple, Deque, Userdict, UserList, UserString. 

How to set the default value of defaultdict in Python?
The default value of the defaultdict can be set by defaultdict(lambda:x), where x is the default value. 

Conclusion

In this blog, we understood the Collections module and its usage in Python. We also learned about different containers the Collections module provides. Python collections module is a powerful addition to the standard library, offering specialized data structures like named tuples, deques, and defaultdicts. These tools simplify complex data handling, making your code more efficient and readable. By leveraging the collections module, you can enhance your programming capabilities and tackle a variety of tasks with ease.

You can refer to our Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass