Python Collections Module

The collections module in Python provides alternatives to the general-purpose built-in containers like dict, list, set, and tuple. It includes useful data types such as Counter, defaultdict, OrderedDict, namedtuple, deque, and more.

Commonly Used Data Types

1. Counter


from collections import Counter
# Example: Counting occurrences of elements in a list
numbers = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
count = Counter(numbers)
print(count)  # Output: Counter({4: 4, 3: 3, 2: 2, 1: 1})
            

Output

Counter({4: 4, 3: 3, 2: 2, 1: 1})

2. defaultdict


from collections import defaultdict
# Example: Using defaultdict to handle missing keys
my_dict = defaultdict(int)
my_dict['apple'] += 1
my_dict['banana'] += 2
print(my_dict)  # Output: defaultdict(, {'apple': 1, 'banana': 2})
            

Output

defaultdict(<class 'int'>, {'apple': 1, 'banana': 2})

3. namedtuple


from collections import namedtuple
# Example: Creating and using namedtuple
Person = namedtuple('Person', ['name', 'age'])
p = Person(name='Alice', age=30)
print(p.name, p.age)  # Output: Alice 30
            

Output

Alice 30

The collections module provides efficient and specialized container data types that can help make your code more readable and performant.