Skip to the solution
MediumDSA13 min read

What useful types does the collections module provide?

964 views

The problem

Question presented to candidate: "Beyond list, dict, set and tuple, Python ships a collections module. Which types in it do you actually use, what problem does each one solve, and when would you pick it over a plain dict or list?"

What a strong answer should cover:

  • Counter (counting, most_common, multiset arithmetic), defaultdict (a factory for missing keys), namedtuple (a tuple with field names), deque (O(1) at both ends, maxlen).
  • OrderedDict still matters after dicts became ordered: move_to_end, popitem(last=False) and order-sensitive equality, the classic LRU building block.
  • ChainMap (layered lookups over several dicts without copying) and UserDict/UserList/UserString (safe bases for subclassing, because a dict subclass's update() skips your __setitem__).
  • Gotchas: reading a missing key creates it in a defaultdict; Counter subtraction drops zero and negative counts; namedtuple is immutable.
  • A version fact: the ABC aliases such as collections.Mapping were removed in 3.10, so import them from collections.abc.

Code / implementation expected: Optional โ€” short snippets per type, ideally a word count with Counter and grouping with defaultdict(list).

  • collections

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

13 min read ยท 14 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonCounter, defaultdict and namedtuple in action
Pythondeque, OrderedDict, ChainMap, and UserDict vs a dict subclass

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 57 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

What are abstract base classes and Protocols?

Continue