# collections & itertools — Python

Source: https://www.geekswithgeeks.com/en/python/py-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.

```python
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.

```python
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')]
```
