Python Collections Module Tutorial | Counter, defaultdict, deque & namedtuple
As applications become larger and more complex, standard Python data structures like lists, dictionaries, and tuples are sometimes not enough. To solve specialized data management problems efficiently, Python provides the collections module.
The collections module contains powerful container data types such as Counter, defaultdict, OrderedDict, deque, namedtuple, and ChainMap. These data structures help developers write cleaner, faster, and more efficient code while reducing complexity.
The collections module is widely used in Artificial Intelligence, Machine Learning, Data Analytics, Backend Development, Automation, Game Development, and Enterprise Applications.
In this lesson, you’ll learn each component of the collections module with practical examples and understand where they should be used in real-world software development.
By the end of this lesson, you’ll be able to replace traditional data structures with more efficient alternatives whenever appropriate.
Learning Objectives
After completing this lesson, you will be able to:
- Understand the Collections Module.
- Use Counter for frequency analysis.
- Work with defaultdict.
- Use OrderedDict.
- Implement deque.
- Create namedtuple objects.
- Merge dictionaries using ChainMap.
- Apply specialized collections in real-world applications.
Topics Covered
- Introduction to Collections Module
- Counter
- defaultdict
- OrderedDict
- deque
- namedtuple
- ChainMap
- Real-World Applications
- Best Practices
Detailed Lesson Content
Introduction to Collections Module
Imagine you’re building an AI-Powered E-Commerce Platform.
Your application needs to:
- Count product purchases.
- Store customer information.
- Manage recently viewed products.
- Process chat messages.
- Organize inventory.
- Merge configuration settings.
Using standard dictionaries and lists may require many lines of code.
Python’s collections module provides specialized data structures that simplify these tasks.
Importing the Collections Module
from collections import *
Or import only the required class.
Example
from collections import Counter
Counter
A Counter counts the frequency of elements in a collection.
Example
from collections import Counter
courses = [
"Python",
"AI",
"Python",
"Django",
"AI",
"Python"
]
count = Counter(courses)
print(count)
Output
Counter({
'Python':3,
'AI':2,
'Django':1
})
Most Common Elements
from collections import Counter
text = "python programming"
counter = Counter(text)
print(counter.most_common(3))
Output
[('p',2),('o',2),('r',2)]
Real-World Example: Student Attendance
from collections import Counter
attendance = [
"Rahul",
"Rahul",
"Amit",
"Rahul",
"Priya"
]
print(Counter(attendance))
defaultdict
A defaultdict automatically assigns a default value if the key does not exist.
Example
from collections import defaultdict
students = defaultdict(int)
students["Rahul"] += 1
students["Rahul"] += 1
print(students)
Output
defaultdict(<class 'int'>,
{'Rahul':2})
No need to check whether the key already exists.
defaultdict with List
from collections import defaultdict
courses = defaultdict(list)
courses["Python"].append("Rahul")
courses["Python"].append("Priya")
print(courses)
Output
{'Python':['Rahul','Priya']}
OrderedDict
An OrderedDict remembers the insertion order of elements.
Example
from collections import OrderedDict
student = OrderedDict()
student["Name"] = "Rahul"
student["Course"] = "Python"
student["Marks"] = 95
print(student)
Although modern Python dictionaries preserve insertion order, OrderedDict still provides additional methods such as move_to_end() and equality comparisons based on order.
deque (Double-Ended Queue)
A deque allows fast insertion and deletion from both ends.
Example
from collections import deque
queue = deque()
queue.append("Rahul")
queue.append("Priya")
queue.appendleft("Admin")
print(queue)
Output
deque(['Admin','Rahul','Priya'])
Removing Elements
queue.pop()
queue.popleft()
print(queue)
Real-World Example: Browser History
from collections import deque
history = deque(maxlen=5)
history.append("Google")
history.append("YouTube")
history.append("OpenAI")
print(history)
Deque automatically removes old entries when the maximum size is reached.
namedtuple
A namedtuple creates lightweight objects with named fields.
Example
from collections import namedtuple
Student = namedtuple(
"Student",
["name","course","marks"]
)
student = Student(
"Rahul",
"Python",
95
)
print(student.name)
print(student.course)
Output
Rahul
Python
Instead of:
student[0]
You can write:
student.name
which is much easier to read.
ChainMap
A ChainMap groups multiple dictionaries into a single view.
Example
from collections import ChainMap
student = {
"name":"Rahul"
}
course = {
"course":"Python"
}
data = ChainMap(
student,
course
)
print(data["course"])
Output
Python
Comparing Standard Dictionary vs defaultdict
Standard Dictionary
students = {}
students["Rahul"] += 1
Output
KeyError
defaultdict
students = defaultdict(int)
students["Rahul"] += 1
Output
1



