Counter, defaultdict, namedtuple
- Use
Counterto count occurrences in a sequence - Use
defaultdictto avoidKeyErrorboilerplate - Use
dequefor O(1) appends and pops on both ends - Use
namedtuplefor lightweight structured records
Counter, defaultdict, and deque are the difference between clean code and reinventing wheels in interviews and production. deque is O(1) at both ends — list.pop(0) is O(n), a bug that quietly slows queue workers.
- Using
dict.get(k, []).append(v)instead ofdefaultdict(list)— the.getversion never mutates the dict. - Using
listas a FIFO queue —pop(0)is O(n); reach forcollections.dequefor O(1) popleft. - Sorting a
Countermanually when.most_common(n)already returns the top-n by count.
The collections module saves you boilerplate.
Counter
A dict subclass that counts hashable items. .most_common(n) is the killer feature.
defaultdict
A dict where missing keys auto-create a default value. defaultdict(list) is the cleanest way to group things.
namedtuple
A tuple with named fields. Tiny, fast, and lets you write p.x instead of p[0]. Modern alternative: dataclasses.dataclass (we'll meet it later).
Try it
- Use
Counterto find the 3 most-common letters in"abracadabra". - Use
defaultdict(int)to count votes from["a","b","a","c","b","a"].
3 graded exercises
Write the code, click Check. We’ll tell you exactly what to fix.
- Exercise 1
Use
collections.Counterto count the letter frequencies in"mississippi". Print the two most common letters as a list of(letter, count)tuples using.most_common(2). Expected:[('i', 4), ('s', 4)]. - Exercise 2
Use
collections.defaultdict(list)to groupwords = ["apple", "ant", "bear", "kite", "kiwi", "bee"]by their first letter intogroups. Then printdict(groups). Expected includes'a': ['apple', 'ant']. - Exercise 3
Use
collections.dequeto implement a sliding window of size 3. Feed the numbers[1, 2, 3, 4, 5]one at a time; after each push, print the current window as a list. Expected 5 lines, last one[3, 4, 5].