Collections Module Overview
The collections module provides specialized container alternatives to Python's built-in containers like list, dict, set, and tuple. Key components include:
namedtuple: Creates tuple subclasses with named fieldsdeque: Double-ended queue for efficient appends/popsCounter: Dictionary subclass for counting hashable objectsOrderedDict: Dictionary that preserves insertion order
Named Tuple Implementation
namedtuple combines tuple benefits with attribute-style access:
Tuple Fundamentals
# Tuple unpacking examples
coordinates = ('x_val', 'y_val')
point = (*coordinates, 'z_val', 'w_val')
x, y = coordinates
first, *remaining = point
print(x, y)
print(first, remaining)
Named Tuple Creation
from collections import namedtuple
Person = namedtuple('Person', ['first_name', 'last_name', 'age'])
# Create instance
p = Person(first_name='Jane', last_name='Doe', age=30)
print(p._fields) # Output: ('first_name', 'last_name', 'age')
# Access attributes
print(p.first_name) # Output: Jane
Advanced Usage
from collections import namedtuple
Employee = namedtuple('Employee', ['id', 'department', 'level'])
# Create from iterable
emp_data = ['E123', 'Engineering', 'L4']
e1 = Employee._make(emp_data)
# Create from dictionary
emp_dict = {'id': 'E456', 'department': 'Marketing', 'level': 'L3'}
e2 = Employee(**emp_dict)
# Field modification
e1 = e1._replace(level='L5')
print(e1._asdict()) # Convert to OrderedDict
Other Collection Types
Counter Implementation
from collections import Counter
class CounterOperations:
def run_examples(self):
c1 = Counter()
words = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
for word in words:
c1[word] += 1
c2 = Counter({'cats': 5, 'dogs': 3})
c3 = Counter(a=3, b=2, c=1, d=0)
print(c1.most_common(2)) # Top 2 frequent items
print(list(c3.elements())) # Non-zero elements
c3.subtract(c1)
print(c3)
c3.update(c2)
print(c3 + c2)
if __name__ == "__main__":
ops = CounterOperations()
ops.run_examples()
Deque Characteristics
Double-ended queues provide efficient O(1) operations for appending and popping from either end, ideal for queue implementations and sliding window algorithms.
Defaultdict Behavior
Automatically initailizes missing keys with default values, reducing key existence checks in dictionary operations.