Counter(iterable) counts occurrences of each item, producing a dict-like object with convenient methods like most_common(). defaultdict(factory) is a dict that automatically creates a default value, like an empty list, for any missing key the first time it's accessed, eliminating manual existence checks. deque is a double-ended queue optimized for fast appends and pops from both ends, unlike a plain list, which is slow at the front. namedtuple creates a lightweight, immutable class with named fields, giving tuple-like performance with attribute-style readability instead of positional indexing.
1Understanding collections Module
Counter(iterable) counts occurrences of each item, producing a dict-like object with convenient methods like most_common(). defaultdict(factory) is a dict that automatically creates a default value, like an empty list, for any missing key the first time it's accessed, eliminating manual existence checks. deque is a double-ended queue optimized for fast appends and pops from both ends, unlike a plain list, which is slow at the front. namedtuple creates a lightweight, immutable class with named fields, giving tuple-like performance with attribute-style readability instead of positional indexing.
Reach for collections.Counter instead of manually building a dict of counts with get-and-increment logic — it's both more concise and provides useful extras like most_common(n) for free.
from collections import Counter
words = ["apple", "banana", "apple", "cherry", "apple"]
counts = Counter(words)
print(counts.most_common(2))2Practical Example
Here is a real-world application of collections Module showing how it is used in production Python code.
from collections import defaultdict
groups = defaultdict(list)
for word in ["cat", "car", "dog", "door"]:
groups[word[0]].append(word)
print(dict(groups))3Best Practices
Follow these guidelines when working with collections Module:
1. Use Counter for counting occurrences instead of manually managing a dict with get(key, 0) + 1 logic
2. Use defaultdict instead of checking whether a key already exists before every insertion into a dict of lists or dicts
3. Use deque instead of list when you need fast insertion/removal from both ends, such as implementing a queue or a sliding window
Tip: Reach for collections.Counter instead of manually building a dict of counts with get-and-increment logic — it's both more concise and provides useful extras like most_common(n) for free.
from collections import Counter
words = ["apple", "banana", "apple", "cherry", "apple"]
counts = Counter(words)
print(counts.most_common(2))