Interview frequency: …
Short answer
Use a list for an ordered, changeable sequence, a tuple for a fixed record, a set for fast membership checks and de-duplication, and a dict to map keys to values with fast lookup.
Explanation
The choice of structure expresses the contract you need: ordering, fast lookup, uniqueness, or key-to-value mapping. A membership test x in list is linear O(n), whereas in a set or dict it is O(1) on average. Since Python 3.7 a dict preserves insertion order as part of the language specification, while a set guarantees no order at all. Use a tuple for composite values that do not change, such as coordinates or compound dict keys.
Code example
allowed = {"admin", "editor"} # set: Fast membership lookup
point = (30.0, 31.2) # tuple: Immutable log
prices = {"apple": 3, "milk": 2} # dict: Key -> value
queue = ["a", "b"] # list: Mutable order
if role in allowed:
...Common mistakes
- Using a list for repeated lookups inside a loop, which turns the algorithm into O(n²).
- Relying on the order of set elements when printing or returning them from an API.
Follow-up questions
- How does the choice of data structure change a program's performance?
- What is the difference between mutable and immutable objects in Python?