📂 Collections Module

Last Updated: 23th August 2025


The collections module is used for working with collections such as lists, sets, and dictionaries in Python.This module gives special container datatypes which are more powerful than normal dict, list, tuple.

List of Functions:

  • collections.Counter(): Returns a new Counter object, which is a dict subclass for counting hashable objects.
from collections import Counter

# example 1
data = ["apple", "banana", "apple", "orange", "banana", "apple"]
c = Counter(data)
print(c)
print(c.most_common(2))

# example 2
reviews = [
    "good product and good quality",
    "bad product but good delivery",
    "excellent quality and good support"
]

words = " ".join(reviews).split()
word_count = Counter(words)
print(word_count)
print(word_count.most_common(3))  # Top 3 frequent words
  • collections.defaultdict(): Returns a new defaultdict object, which is a dict subclass that calls a factory function to supply missing values.
from collections import defaultdict
# example 1
dd = defaultdict(int)   # default value = 0
dd["a"] += 1
dd["b"] += 5
print(dd["c"])  # not defined but gives 0
print(dd)

# example 2
d = defaultdict(list)
d["a"].append(1)
d["a"].append(2)
print(d)  # defaultdict(<class 'list'>, {'a': [1, 2]})

# example 3
students = [
    ("sam", "Data Science"),
    ("Avi", "Web Dev"),
    ("Shiv", "Data Science"),
    ("Suraj", "AI"),
]

courses = defaultdict(list)
for name, course in students:
    courses[course].append(name)

print(dict(courses))
  • collections.namedtuple(typename, field_names): Returns a new subclass of tuple with named fields.
from collections import namedtuple

# example 1
Point = namedtuple("Point", ["x", "y"])
pt = Point(1, 2)
print(pt)
print(pt.x, pt.y)

# example 2
Employee = namedtuple("Employee", ["id", "name", "salary"])
emp1 = Employee(101, "Aman", 70000)
emp2 = Employee(102, "Rahul", 80000)
print(emp1.name, emp2.salary)
  • collections.ChainMap(): Returns a new ChainMap object, which is Combines multiple dictionaries and searches them as one.
from collections import ChainMap
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
cm = ChainMap(dict1, dict2)
print(cm["a"], cm["b"], cm["c"]) # take value of b from dict1
  • collections.deque(): Returns a new deque object, which is a double-ended queue.Fast append & pop from both sides.
from collections import deque

# example 1
d = deque()
d.append(1)
d.append(2)
d.appendleft(3)
print(d)  # deque([3, 1, 2])

# example 2
temperatures = [30, 32, 35, 33, 36, 38, 37]
window = deque(maxlen=3)

for t in temperatures:
    window.append(t)
    print(f"Last 3 days avg: {sum(window)/len(window)}")
  • collections.OrderedDict(): Returns a new OrderedDict object, which is a dict subclass that remembers the order of insertion (Python 3.7+ normal dict also keeps order, but OrderedDict has extra features) like move_to_end(key), move_to_front(key) etc.
from collections import OrderedDict
od = OrderedDict()
od["one"] = 1
od["two"] = 2
od["three"] = 3
print(od)  # OrderedDict([('one', 1), ('two', 2), ('three', 3)])
od.move_to_end("one")
print(od)  # OrderedDict([('two', 2), ('three', 3), ('one', 1)])
od.move_to_front("one")
print(od)  # OrderedDict([('one', 1), ('two', 2), ('three', 3)])