Lesson 41 / 47

collections & itertools

Specialized containers and building blocks for loops, beyond the built-ins.

Counter & defaultdict

Counter tallies items instantly; defaultdict supplies a default value instead of raising KeyError on a missing key.

from collections import Counter, defaultdict

words = ["cat", "dog", "cat", "bird", "cat"]
print(Counter(words))   # Counter({'cat': 3, 'dog': 1, 'bird': 1})

groups = defaultdict(list)
groups["fruit"].append("apple")   # no KeyError, list() is auto-created
print(groups)

itertools basics

itertools offers memory-efficient tools for combining and looping — chain, product, combinations are the most-used.

from itertools import chain, combinations

print(list(chain([1, 2], [3, 4])))          # [1, 2, 3, 4]
print(list(combinations("ABC", 2)))         # [('A','B'), ('A','C'), ('B','C')]