Guide Python Beginner

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.

2 min read

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

in and not in test whether a value is present in (or absent from) a collection, returning a bool — checking dict membership tests keys by default. The performance characteristics differ sharply by container: in is O(n) on a list, since it has to scan element by element, but O(1) average on a set or dict, since both use hashing under the hood. Any code doing repeated membership checks against a large collection should convert it to a set first.”

Common Mistakes

  • Repeatedly checking x in some_list inside a loop against a large list instead of converting it to a set once beforehand — an easy, invisible performance cliff at scale.
  • Forgetting in on a dict checks keys, not values — use value 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