Skip to the solution
EasyDSA10 min read

How does the in operator work in Python?

451 views

The problem

Question presented to candidate: "When you write x in something, what does Python actually do? Does it cost the same for a list, a set and a string, and how would you make your own class support in?"

What a strong answer should cover:

  • x in y calls type(y).__contains__(y, x) when it exists; otherwise Python iterates y with __iter__; otherwise it tries the old __getitem__ protocol with indexes 0, 1, 2 ... until IndexError; otherwise TypeError.
  • The result is always a bool (whatever __contains__ returns is converted), and not in is the exact negation; in bytecode both are one CONTAINS_OP instruction.
  • Cost depends on the container: hash lookup, O(1) on average, for set, frozenset, dict and dict key views; a linear O(n) scan for list, tuple, dict.values() and iterators; substring search for str and bytes; arithmetic for an int in a range.
  • Sequences test identity before equality (x is e or x == e), which is why nan in [nan] is True.
  • Gotchas: in on a dict checks keys only; sets need a hashable left operand; in on an iterator consumes it; a float in a range falls back to a scan.

Code / implementation expected: Optional β€” a class with __contains__, or a demonstration of set vs list membership cost.

  • in
  • contains

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

10 min read Β· 10 sections

Run the code

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

Pythonin on lists, strings, dicts, ranges and sets
PythonThe protocol: __contains__, __iter__, __getitem__ fallbacks
PythonCounting == calls: list scan vs set lookup

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 24 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 nextEasy

What are Python's built-in data types?

Continue