the full guide

collections and itertools

collections provides specialised containers such as Counter, defaultdict, deque and namedtuple. itertools provides tools for efficient looping, such as combinations, permutations, chain and groupby.

10 min Intermediate

What you need: The earlier topics of this module.

Definition

collections provides specialised containers such as Counter, defaultdict, deque and namedtuple. itertools provides tools for efficient looping, such as combinations, permutations, chain and groupby.

In simple words

These are the expert tools in Python's toolbox. Why write a counting loop when Counter does it in one word?

Why it matters

They turn common jobs like counting words, or building a vocabulary in NLP, into a line or two, and they run fast.

How it works

ToolUse
CounterCount things, and find the most common
defaultdictA dict that creates missing keys
dequeFast add and remove at both ends
namedtupleA tuple with named fields
combinationsChoose r items, order ignored
permutationsArrange r items, order matters
chainJoin several iterables

In code

collections_demo.py
from collections import Counter, defaultdict, deque, namedtuple
from itertools import chain, combinations

print(Counter("the cat and the dog".split()).most_common(1))

groups = defaultdict(list)
for name in ["Asha", "Aman", "Riya"]:
    groups[name[0]].append(name)
print(dict(groups))

queue = deque([1, 2, 3])
queue.appendleft(0)
print(queue.popleft(), list(queue))

Point = namedtuple("Point", "x y")
print(Point(2, 3).x)

print(list(combinations("ABC", 2)))
print(list(chain([1, 2], [3])))

Output

[('the', 2)]
{'A': ['Asha', 'Aman'], 'R': ['Riya']}
0 [1, 2, 3]
2
[('A', 'B'), ('A', 'C'), ('B', 'C')]
[1, 2, 3]

Common mistakes

  • Using list.pop(0) as a queue. It gets slow on big lists. Use deque.
  • Using groupby on unsorted data. It only groups neighbours, so sort first.

Check yourself

Question 1

1. Which suits counting word frequencies?

Question 2

2. How many pairs does combinations("ABC", 2) give?

Summary

  • collections gives smarter containers.
  • itertools gives efficient looping tools.

Finished reading?

Sources: Python docs: collections · Python docs: itertools