Python Collections Module: Enhancing Container Data Types

Explore the Python collections module, which offers alternatives to built-in container data types like lists, tuples, and dictionaries. Learn about key functions such as namedtuple(), which provides tuple-like objects with named fields accessible by both lookup and index.



Python - Collections Module

The collections module in Python provides alternatives to built-in container data types such as list, tuple, and dict. Here are some of its notable functions:

namedtuple()

The namedtuple() function returns a tuple-like object with named fields. These field attributes are accessible by lookup as well as by index.

Syntax

collections.namedtuple(type_name, field-list)
Example: namedtuple()

import collections

# Define a namedtuple for 'student' with fields 'name', 'age', 'marks'
student = collections.namedtuple('student', ['name', 'age', 'marks'])

# Create an instance of student
s1 = student("Imran", 21, 98)

# Access fields using attribute names and indices
print(s1.name)
print(s1.age)
print(s1.marks)

print(s1[0])
print(s1[1])
print(s1[2])
Output

Imran
21
98
Imran
21
98

OrderedDict()

The OrderedDict() function is similar to a normal dictionary object in Python. However, it remembers the order of the keys in which they were first inserted.

Example: OrderedDict()

import collections

# Create an OrderedDict
d1 = collections.OrderedDict()
d1['A'] = 65
d1['C'] = 67
d1['B'] = 66
d1['D'] = 68

# Iterate over OrderedDict
for k, v in d1.items():
    print(k, v)
Output

A 65
C 67
B 66
D 68

deque()

A deque object support appends and pops from either ends of a list. It is more memory efficient than a normal list object. In a normal list object, the removal of any item causes all items to the right to be shifted towards left by one index. Hence, it is very slow.

Example: deque()

import collections

# Create a deque
q = collections.deque([10, 20, 30, 40])

# Append elements
q.appendleft(0)
print(q)

q.append(50)
print(q)

# Pop elements
print(q.pop())
print(q)

print(q.popleft())
print(q)
Output

deque([0, 10, 20, 30, 40])
deque([0, 10, 20, 30, 40, 50])
50
deque([0, 10, 20, 30, 40])
0
deque([10, 20, 30, 40])