← All topics
Arrays & Hashing
Lists, dicts, sets, and counting patterns.
Arrays & Hashing
The bread and butter: lists for ordered data, dicts and sets for O(1) lookup.
Core syntax
- Frequency count —
Counter(nums)or adefaultdict(int)withcount[x] += 1. - Group by key —
defaultdict(list)thengroups[key].append(x). - Membership —
x in seenwhereseenis aset(O(1), not a list). - Index map —
{v: i for i, v in enumerate(nums)}.
from collections import Counter, defaultdict
freq = Counter(nums) # {val: count}
groups = defaultdict(list)
for s in strs:
groups[tuple(sorted(s))].append(s)
Watch out
{}is an empty dict, not a set — useset().dict.get(k, default)avoidsKeyError.