ProgrammingModerateProduct-company MCQ pattern

Which operation is O(1) on average in CPython?

  1. A. Checking membership with x in a list
  2. B. Calling list.index(x) on a list of n items
  3. C. Calling str.count on a string of n characters
  4. D. Looking up a value by key in a dict

Correct answer: D. Looking up a value by key in a dict

A dict uses hashing to find a key's slot in about constant time on average. The other three each scan the container, which costs O(n).

More Python Programming questions

Exams that ask this topic