0
0
PythonHow-ToBeginner · 4 min read

How to Use Collections Module in Python: Syntax and Examples

The collections module in Python provides specialized container datatypes like Counter, defaultdict, and namedtuple to handle data more efficiently. You use it by importing collections and then creating or manipulating these data structures as needed.
📐

Syntax

Import the collections module to access its specialized container types. Common classes include:

  • Counter: Counts hashable objects.
  • defaultdict: Dictionary with default values.
  • namedtuple: Tuple with named fields.
  • deque: Double-ended queue for fast appends/pops.

Example syntax to import and use:

python
import collections

# Create a Counter
c = collections.Counter(['a', 'b', 'a'])

# Create a defaultdict with default int
d = collections.defaultdict(int)
d['key'] += 1

# Create a namedtuple
Point = collections.namedtuple('Point', ['x', 'y'])
p = Point(1, 2)

# Create a deque
dq = collections.deque([1, 2, 3])
💻

Example

This example shows how to count items, use a dictionary with default values, create a named tuple, and use a deque for fast queue operations.

python
import collections

# Count letters in a word
word = 'banana'
counter = collections.Counter(word)
print('Counter:', counter)

# defaultdict example
freq = collections.defaultdict(int)
for letter in word:
    freq[letter] += 1
print('defaultdict:', dict(freq))

# namedtuple example
Point = collections.namedtuple('Point', ['x', 'y'])
p = Point(10, 20)
print('namedtuple:', p, 'x:', p.x, 'y:', p.y)

# deque example
queue = collections.deque()
queue.append('first')
queue.append('second')
print('deque before pop:', list(queue))
queue.popleft()
print('deque after pop:', list(queue))
Output
Counter: Counter({'a': 3, 'n': 2, 'b': 1}) defaultdict: {'b': 1, 'a': 3, 'n': 2} namedtuple: Point(x=10, y=20) x: 10 y: 20 deque before pop: ['first', 'second'] deque after pop: ['second']
⚠️

Common Pitfalls

Common mistakes when using the collections module include:

  • Not importing the module before use.
  • Using defaultdict without a default factory function, causing errors.
  • Modifying a namedtuple like a normal tuple (they are immutable).
  • Using Counter expecting it to return missing keys as zero without checking.

Example of wrong and right usage of defaultdict:

python
import collections

# Wrong: defaultdict without factory
try:
    d = collections.defaultdict()
    d['key'] += 1
except TypeError as e:
    print('Error:', e)

# Right: defaultdict with int factory
d = collections.defaultdict(int)
d['key'] += 1
print('Correct defaultdict:', dict(d))
Output
Error: first argument must be callable or None Correct defaultdict: {'key': 1}
📊

Quick Reference

ClassPurposeExample Usage
CounterCount hashable objectscollections.Counter(['a', 'b', 'a'])
defaultdictDictionary with default valuescollections.defaultdict(int)
namedtupleTuple with named fieldscollections.namedtuple('Point', ['x', 'y'])
dequeDouble-ended queuecollections.deque([1, 2, 3])

Key Takeaways

Import the collections module to access specialized container types.
Use Counter to count items, defaultdict for default values, namedtuple for readable tuples, and deque for fast queue operations.
Always provide a default factory function when creating a defaultdict.
namedtuple instances are immutable; you cannot change their fields after creation.
collections module helps write cleaner and more efficient code for common data tasks.