L2·Control & Collections

🧺collections: Counter, deque, defaultdict

Specialised containers every interviewer expects you to know.

CounterdequedefaultdictnamedtupleOrderedDict

§ 1Counter

Counts hashable items. most_common(n) returns the top n.

1from collections import Counter​
2print(Counter("banana").most_common(2)) # [('a', 3), ('n', 2)]​

§ 2defaultdict

A dict that creates a default value for missing keys — perfect for grouping.

1from collections import defaultdict​
2g = defaultdict(list)​
3g["fruit"].append("apple")​

§ 3deque

Double-ended queue with O(1) append/pop at both ends. Use it for BFS and sliding windows; list.pop(0) is O(n).

§ 4namedtuple

Lightweight immutable record with named fields: Point = namedtuple('Point', 'x y').

Worked example

1from collections import Counter, defaultdict, deque​
2​
3words = "the cat and the hat and the bat".split()​
4print(Counter(words).most_common(1))​
5​
6by_len = defaultdict(list)​
7for w in words:​
8 by_len[len(w)].append(w)​
9print(dict(by_len))​
10​
11q = deque([1, 2, 3])​
12q.appendleft(0); q.append(4)​
13print(q.popleft(), q.pop(), list(q))​

Try it live · Python runs in your browser

Loading playground…

Checkpoint quiz

Question 1 / 2
Best structure for a BFS queue:

Lesson test

Take an 8-question test on “collections: Counter, deque, defaultdict” — concepts, output prediction, bug spotting and interview questions.