Collections Module
The collections module provides advanced and specialized data structures that extend Python's built-in types like lists, tuples, dictionaries, and sets.
Key Features of Collections Module
Counter
A Counter counts the occurrences of elements in a list, string, or other iterable.
Example:
from collections import Counter # Count characters in a string text = "hello world" counter = Counter(text) print(counter) # Output: Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1}) # Count elements in a list numbers = [1, 2, 2, 3, 3, 3] print(Counter(numbers)) # Output: Counter({3: 3, 2: 2, 1: 1})
NamedTuple
A namedtuple creates lightweight objects like tuples but allows you to assign meaningful names to their elements.
Example:
from collections import namedtuple # Define a namedtuple Point = namedtuple("Point", "x y") p = Point(10, 20) print(p.x, p.y) # Output: 10 20
defaultdict
A defaultdict automatically provides a default value for missing keys in a dictionary.
Example:
from collections import defaultdict # Create a defaultdict with default type int numbers = defaultdict(int) numbers['a'] += 1 print(numbers['a']) # Output: 1 print(numbers['b']) # Output: 0 (default value)
deque
A deque (double-ended queue) is a list-like structure that allows adding and removing elements from both ends efficiently.
Example:
from collections import deque dq = deque([1, 2, 3]) dq.append(4) # Add to the right dq.appendleft(0) # Add to the left print(dq) # Output: deque([0, 1, 2, 3, 4]) dq.pop() # Remove from the right dq.popleft() # Remove from the left print(dq) # Output: deque([1, 2, 3])
OrderedDict
An OrderedDict remembers the order in which items are inserted into a dictionary (in Python 3.7+, regular dict also maintains insertion order).
Example:
from collections import OrderedDict od = OrderedDict() od['a'] = 1 od['b'] = 2 od['c'] = 3 print(od) # Output: OrderedDict([('a', 1), ('b', 2), ('c', 3)])
ChainMap
A ChainMap combines multiple dictionaries into one view for easy access to their combined data.
Example:
from collections import ChainMap dict1 = {'a': 1, 'b': 2} dict2 = {'b': 3, 'c': 4} cm = ChainMap(dict1, dict2) print(cm['b']) # Output: 2 (from dict1) print(cm['c']) # Output: 4 (from dict2)