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 ycallstype(y).__contains__(y, x)when it exists; otherwise Python iteratesywith__iter__; otherwise it tries the old__getitem__protocol with indexes 0, 1, 2 ... untilIndexError; otherwiseTypeError.- The result is always a
bool(whatever__contains__returns is converted), andnot inis the exact negation; in bytecode both are oneCONTAINS_OPinstruction. - Cost depends on the container: hash lookup, O(1) on average, for
set,frozenset,dictand dict key views; a linear O(n) scan forlist,tuple,dict.values()and iterators; substring search forstrandbytes; arithmetic for anintin arange. - Sequences test identity before equality (
x is e or x == e), which is whynan in [nan]isTrue. - Gotchas:
inon a dict checks keys only; sets need a hashable left operand;inon an iterator consumes it; a float in arangefalls back to a scan.
Code / implementation expected: Optional β a class with __contains__, or a demonstration of set vs list membership cost.