`in` checks for membership by calling the container's __contains__ method, or falling back to iteration if that's not defined, and its performance depends heavily on the container type: checking a list or tuple is O(n), since it may scan every element, while checking a set or dict is average O(1) thanks to hashing. For a dict specifically, `in` checks the keys, not the values, unless you explicitly check the values view.
1Understanding Membership Operators
in checks for membership by calling the container's __contains__ method, or falling back to iteration if that's not defined, and its performance depends heavily on the container type: checking a list or tuple is O(n), since it may scan every element, while checking a set or dict is average O(1) thanks to hashing. For a dict specifically, in checks the keys, not the values, unless you explicitly check the values view.
If you're doing repeated `in` checks against the same collection inside a loop, convert it to a set first — turning an O(n) scan per check into an O(1) lookup can make a big difference on large inputs.
fruits = ["apple", "banana", "cherry"]
print("banana" in fruits)
print("grape" not in fruits)2Practical Example
Here is a real-world application of Membership Operators showing how it is used in production Python code.
config = {"debug": True, "env": "prod"}
print("debug" in config)
print(True in config.values())3Best Practices
Follow these guidelines when working with Membership Operators:
1. Convert a list to a set before doing many repeated in checks against it, for O(1) average lookups instead of O(n)
2. Remember membership checks on a dict test its keys by default — check its values view explicitly to test values instead
3. Use not in directly instead of negating an in expression, for readability
Tip: If you're doing repeated `in` checks against the same collection inside a loop, convert it to a set first — turning an O(n) scan per check into an O(1) lookup can make a big difference on large inputs.
fruits = ["apple", "banana", "cherry"]
print("banana" in fruits)
print("grape" not in fruits)