7.7 Membership Operators
Python's in and not in operators for testing whether a value exists in a collection, and why converting to a set matters for repeated membership checks.
in
What Is It?
Tests whether a value exists within a collection (list, string, dict keys, and so on), returning a bool.
>>> 3 in [1, 2, 3]
True
>>> "a" in "cat"
True
>>> "key" in {"key": 1} # checks dict KEYS by default
True
not in
The negation of in — tests for absence.
>>> 5 not in [1, 2, 3]
True
Searching Collections
Performance Note
in is O(n) on a list but O(1) average on a set or dict — see 5.6 Set Data Types. Convert to a set first if checking membership repeatedly against a large collection.
Validation Example
allowed_regions = {"us-east-1", "us-west-2", "eu-west-1"}
region = "us-east-1"
>>> region in allowed_regions
True
Quick Interview Answer
“
inandnot intest whether a value is present in (or absent from) a collection, returning abool— checking dict membership tests keys by default. The performance characteristics differ sharply by container:inis O(n) on alist, since it has to scan element by element, but O(1) average on asetordict, since both use hashing under the hood. Any code doing repeated membership checks against a large collection should convert it to asetfirst.”
Common Mistakes
- Repeatedly checking
x in some_listinside a loop against a large list instead of converting it to asetonce beforehand — an easy, invisible performance cliff at scale. - Forgetting
inon adictchecks keys, not values — usevalue in d.values()explicitly if that’s what’s actually needed.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form