Core Data Structures
Lists, tuples, dicts, and sets — their underlying implementations and when each is the right choice.
Try answering in your head first, then click a question to check the model answer.
Q1.When would you choose a tuple over a list?(show answer)
When the collection shouldn't change after creation — e.g. as a dict key (tuples are hashable if their elements are), a fixed record like coordinates, or to signal intent that the data is immutable. Tuples are also slightly more memory-efficient.
Q2.Why is set/dict membership testing O(1) average case, and when does it degrade?(show answer)
Sets and dicts are backed by a hash table — the key's hash determines its bucket directly, avoiding a linear scan. It degrades toward O(n) worst case with many hash collisions (rare with a good hash function) or if __hash__ is poorly implemented for custom objects.
Q3.What's the amortized time complexity of `list.append()`, and why not the worst case per call?(show answer)
Amortized O(1). CPython over-allocates extra capacity when a list grows, so most appends are a cheap O(1) write into existing space; occasionally the list must be resized and copied (O(n)), but that cost is spread — amortized — across the many O(1) appends between resizes.
Q4.What makes an object unhashable in Python, and what's a common example?(show answer)
An object is unhashable if it's mutable and its __hash__ is set to None (or absent) — because a hashable object's value must not change after insertion, or it could no longer be found in its original bucket. Lists and dicts are the classic unhashable examples; tuples and frozensets are their hashable, immutable counterparts.
