Python __contains__ Method
Last modified November 17, 2026 Python 3.15
The in and not in operators ask a container whether it
holds a value. For a user-defined class the answer comes from
__contains__, a method that receives the value and returns
something that Python interprets as true or false. This article shows the
dispatch order, the exact moment the truth value is evaluated, the fallbacks
used when the method is missing, and several patterns for containers whose
membership rule is not a simple list scan.
The in operator and __contains__
x in container is evaluated as
type(container).__contains__(container, x). The method is looked up
on the type, so a subclass can override the rule without touching the caller.
The next example wraps a list and prints every check, which makes the number of
calls visible for both in and not in.
class Bag:
def __init__(self, items):
self.items = list(items)
def __contains__(self, item):
print(f"checking {item!r}")
return item in self.items
bag = Bag(["apple", "banana", "cherry"])
print("banana" in bag)
print("kiwi" in bag)
print("kiwi" not in bag)
Each expression calls __contains__ exactly once; not in
does not call a separate method, it negates the same result. Here the wrapper
delegates to the list, but it could apply normalization, query an index, or
compute the answer from a formula instead of storing the items at all.
$ python basic.py checking 'banana' True checking 'kiwi' False checking 'kiwi' True
The result is converted to bool
Strictly speaking, __contains__ may return any object. The
interpreter passes the result through bool(), so a custom object
with a __bool__ method is evaluated at that point. This matters for
lazy containers and for objects such as NumPy arrays, whose truth value is not
always a plain boolean.
class Result:
def __init__(self, value):
self.value = value
def __bool__(self):
print("bool() called")
return self.value
class Checker:
def __contains__(self, item):
print(f"__contains__({item!r})")
return Result(item == "yes")
checker = Checker()
print("yes" in checker)
print("no" in checker)
print("no" not in checker)
The __contains__ call is followed by a bool() call, and
only then does in produce its answer. Returning a truthy object is
therefore allowed, but returning a boolean is clearer and avoids an extra
protocol step. A generator or an empty list is a poor return value: it is always
truthy, so the membership test would always succeed.
$ python truthiness.py
__contains__('yes')
bool() called
True
__contains__('no')
bool() called
False
__contains__('no')
bool() called
True
Fallbacks when __contains__ is missing
A class without __contains__ can still support in.
Python first tries __iter__ and compares each yielded element, and
if even iteration is unavailable it uses __getitem__ with increasing
integer indices until an IndexError is raised. The fallbacks are
convenient but can be much slower than a dedicated method.
class IterOnly:
def __iter__(self):
print("__iter__ called")
return iter([10, 20, 30])
class GetItemOnly:
def __getitem__(self, index):
print("__getitem__ called with", index)
if index >= 3:
raise IndexError(index)
return index * 10
print(20 in IterOnly())
print(20 in GetItemOnly())
print(35 in GetItemOnly())
IterOnly is scanned through its iterator, and the search stops as
soon as 20 is produced. GetItemOnly is probed from index 0 upward;
the successful search ends at index 2, while the unsuccessful one reads 0, 1, 2,
and finally 3, where IndexError ends the sequence. The index
fallback exists for old sequence-like classes, but new code should provide
__iter__ or, better, __contains__.
$ python fallback.py __iter__ called True __getitem__ called with 0 __getitem__ called with 1 __getitem__ called with 2 True __getitem__ called with 0 __getitem__ called with 1 __getitem__ called with 2 __getitem__ called with 3 False
Containers defined by a rule
Not every container stores its members. A case-insensitive word set and a set of port ranges can answer membership by normalizing the query or by checking interval bounds. Both classes below also reject values of the wrong type instead of raising an error, which is usually the friendlier behaviour for a membership test.
class CaseInsensitive:
def __init__(self, words):
self.words = {word.casefold() for word in words}
def __contains__(self, word):
return isinstance(word, str) and word.casefold() in self.words
class Ranges:
def __init__(self, *intervals):
self.intervals = intervals
def __contains__(self, value):
if not isinstance(value, (int, float)):
return False
return any(start <= value <= end for start, end in self.intervals)
fruits = CaseInsensitive(["Apple", "Banana", "Orange"])
print("APPLE" in fruits)
print(" pear " in fruits)
ports = Ranges((8000, 8099), (9000, 9099))
print(8080 in ports)
print(8500 in ports)
print("8080" in ports)
The word set stores folded strings, so "APPLE" matches regardless
of case; the lookup with surrounding spaces fails because it is a different
string, and trimming would have to be added explicitly. The ranges class accepts
numbers inside either interval and returns False for the string
"8080" rather than letting a comparison raise
TypeError. Deciding the type policy is part of the container's
contract.
$ python predicates.py True False True False False
Hashed storage and unhashable values
A container backed by a set or a dictionary gets average constant-time lookups,
but the query must be hashable. Passing a list to a set lookup raises
TypeError, so a robust __contains__ catches that case
and returns False when the value can never be a member.
class Tags:
def __init__(self, tags):
self.tags = frozenset(tags)
def __contains__(self, tag):
try:
return tag in self.tags
except TypeError:
return False
tags = Tags(["python", "sqlite", "asyncio"])
print("python" in tags)
print("rust" in tags)
print(["python"] in tags)
The list is unhashable, and without the except clause the last
expression would fail with TypeError: unhashable type: 'list'.
Returning False is reasonable here, because a list cannot equal any
of the stored strings. A membership test that accepts arbitrary user input
should decide deliberately whether invalid types are errors or simply
non-members.
$ python hashed.py True False False
Containment without iteration
__contains__ does not have to scan. A binary search tree can decide
membership by following one path from the root, comparing the value at each
node. The method below also counts the comparisons, which shows that the work
depends on the height of the tree rather than on the number of stored values.
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class Tree:
def __init__(self, values=()):
self.root = None
for value in values:
self.add(value)
def add(self, value):
if self.root is None:
self.root = Node(value)
return
node = self.root
while True:
if value < node.value:
if node.left is None:
node.left = Node(value)
return
node = node.left
else:
if node.right is None:
node.right = Node(value)
return
node = node.right
def __contains__(self, value):
node = self.root
steps = 0
while node is not None:
steps += 1
if value == node.value:
print(f"found after {steps} steps")
return True
node = node.left if value < node.value else node.right
print(f"not found after {steps} steps")
return False
tree = Tree([5, 3, 8, 1, 4, 7, 9])
print(4 in tree)
print(6 in tree)
print(9 not in tree)
The value 4 is found after three comparisons: 5, 3, then 4. The missing value 6
also takes three comparisons and ends at a None child. The last
expression shows not in reusing the same method. Because
__contains__ is part of the sequence protocol, the tree can also be
used in code that expects a container, without exposing its internal nodes.
$ python tree.py found after 3 steps True not found after 3 steps False found after 3 steps False
Best practices
Membership is a question, so keep the answer cheap and predictable:
- Return a boolean, not a generator or a non-empty collection; any truthy object would make every test succeed.
- Implement
__contains__when the container can answer faster than a full scan, for example with a set, an index, or a range check. - Keep
__contains__consistent with__iter__and__getitem__; a value thatinreports must be findable by iteration. - Decide explicitly how to treat values of the wrong type; returning
Falseis often better than raising from deep inside a lookup. - Remember that
not incalls the same method; there is no separate negative hook. - Do not mutate the container during the check, and avoid expensive work that the caller did not ask for.
Source
object.__contains__ - Python documentation
Membership test operations - Python documentation
Container types - Python documentation
In this article we have implemented the __contains__ method. We have
covered the in dispatch, truth-value conversion, the
__iter__ and __getitem__ fallbacks, rule-based
containers, hashed storage with unhashable queries, and a tree that answers
membership without iteration. For related topics, see
Python __iter__ method,
Python __getitem__ method,
Python __eq__ method, and
Python any and all functions.
Author
List all Python tutorials.