Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Data types & structuresMiddleCommonDesign

How should you decide between a list, a set and a dict for a lookup-heavy piece of code?

Answer

Membership testing (`x in container`) is O(n) on a list because it scans element by element, but average O(1) on a set or a dict because both use hashing. If you need to check membership repeatedly and do not need order or key-value pairing, a set is the right structure. If you need to associate each key with an extra piece of data, a dict gives you the same O(1) lookup plus that associated value. Lists remain the right choice when order and duplicate values matter more than lookup speed.

Strong answer includes

  • list membership test is O(n), set/dict are average O(1)
  • set for pure membership, dict for key-to-value lookup
  • list when order and duplicates matter more than lookup speed

Practical example

Replacing

Python example
if user_id in list_of_ids:

inside a loop with

Python example
if user_id in set_of_ids:

can turn an O(n²) validation pass into an O(n) one for a large dataset.

#performance#data-structures#design

Sources

The Python Standard LibraryPython Software Foundation · Authoritative behavior for built-in types and standard library modules