collections Module
Python · Intermediate
Definition
collections offers Counter, defaultdict, deque, namedtuple and OrderedDict for common patterns.
Shortens DSA solutions dramatically.
Diagram
Flowchart
Example: Group anagrams
from collections import defaultdict
g = defaultdict(list)
for w in ['eat', 'tea', 'tan', 'nat']:
g[''.join(sorted(w))].append(w)
print(list(g.values()))Output: [['eat', 'tea'], ['tan', 'nat']]
Key points
- Counter supports + and − of counts
- heapq pairs well for top-k
Interview questions
dict vs defaultdict?
defaultdict creates a default value for missing keys instead of raising KeyError.