collections for better data structures
collections contains data structures that often fit real problems better than plain lists or dictionaries. A few tools in this module can make code both shorter and clearer.
Why it is useful
The most practical tools here are:
Counterfor frequency countingdefaultdictfor grouping and accumulatingdequefor efficient append and pop operations at both endsnamedtuplewhen a lightweight structured record is enough
Each one makes the intended data shape more obvious.
A few high-value patterns
Counting:
from collections import Counter
counts = Counter(["a", "b", "a"])
print(counts["a"])
Grouping:
from collections import defaultdict
groups = defaultdict(list)
groups["python"].append("tips")
Queue-like behavior:
from collections import deque
items = deque([1, 2, 3])
items.appendleft(0)
print(items.popleft())
When not to use it
Do not reach for these types just because they exist. Use them when they match the actual job better than a normal list or dictionary.
Rules of thumb
- Use
Counterfor counts, not hand-rolled dictionaries. - Use
defaultdictwhen missing-key setup keeps repeating. - Use
dequewhen operations at the left side matter. - Let the data structure communicate the task.