🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
REFERENCEpython

python Documentation

LOADING ENGINE...

collections Module

AI & DATA SCIENCE // collections-module

The collections module provides specialized container data types beyond list, dict, tuple, and set — like Counter, defaultdict, deque, and namedtuple — each optimized for a specific common pattern.

Syntax

from collections import Counter, defaultdict, deque, namedtuple

Deep Dive Course

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.

editor.html
from collections import Counter

words = ["apple", "banana", "apple", "cherry", "apple"]
counts = Counter(words)
print(counts.most_common(2))
localhost:3000

2Practical Example

Here is a real-world application of collections Module showing how it is used in production Python code.

editor.html
from collections import defaultdict

groups = defaultdict(list)
for word in ["cat", "car", "dog", "door"]:
    groups[word[0]].append(word)
print(dict(groups))
localhost:3000

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.

editor.html
from collections import Counter

words = ["apple", "banana", "apple", "cherry", "apple"]
counts = Counter(words)
print(counts.most_common(2))
localhost:3000

Examples

Example 01Basic Usage
from collections import Counter

words = ["apple", "banana", "apple", "cherry", "apple"]
counts = Counter(words)
print(counts.most_common(2))
Example 02Advanced Example
from collections import defaultdict

groups = defaultdict(list)
for word in ["cat", "car", "dog", "door"]:
    groups[word[0]].append(word)
print(dict(groups))

Best Practices

  • Use Counter for counting occurrences instead of manually managing a dict with get(key, 0) + 1 logic
  • Use defaultdict instead of checking whether a key already exists before every insertion into a dict of lists or dicts
  • Use deque instead of list when you need fast insertion/removal from both ends, such as implementing a queue or a sliding window

Interview Question

How does defaultdict avoid the need to check whether a key already exists before appending to it?

Hint: Think about what happens the moment a missing key is accessed.

defaultdict is constructed with a factory function; the first time any missing key is accessed, whether for reading or for an operation like appending to it, defaultdict automatically calls that factory to create a default value, like an empty list, inserts it under that key, and then proceeds with the operation. This means code can immediately append to a value under a brand-new key even if that key has never been seen before, without a preceding existence check, since the empty list is created on demand.

Exercises

MediumPractice using collections Module in a real scenario.
View Solution
from collections import Counter

words = ["apple", "banana", "apple", "cherry", "apple"]
counts = Counter(words)
print(counts.most_common(2))

Frequently Asked Questions

How does defaultdict avoid the need to check whether a key already exists before appending to it?

defaultdict is constructed with a factory function; the first time any missing key is accessed, whether for reading or for an operation like appending to it, defaultdict automatically calls that factory to create a default value, like an empty list, inserts it under that key, and then proceeds with the operation. This means code can immediately append to a value under a brand-new key even if that key has never been seen before, without a preceding existence check, since the empty list is created on demand.

Related Functions

dictionariesliststuples