PythonPython Operators and ExpressionsPython membership operators
What is the membership operator in Python?
Question 46 of 88 · Updated
On this page
- 1. Membership syntax and basic behavior
- 2. Membership depends on the container
- 3. Dictionary membership checks keys, not values
- 4. Sets, ranges and efficient lookups
- 5. How Python resolves the membership protocol
- 6. Custom containment with __contains__
- 7. Iteration and legacy sequence fallback
- 8. Membership can consume an iterator
- 9. Element identity and equality
- 10. Bytes membership
- 11. Membership time complexity
- 12. Practical example: validate supported file suffixes
- 13. Practical example: filter records using a lookup set
- 14. Common membership errors
- Frequently asked questions
- What is the difference between in and not in?
- Can in search a string?
- Does in search dictionary values?
- Is set membership faster than list membership?
- Does membership work with generators?
- Can I customize the membership operator?
- Interview-ready answer
- Official references
Python's membership operators are in and not in. They determine whether an object belongs to a container, matches an element of an iterable or satisfies another object's containment contract. The expression value in container returns True if membership succeeds, and value not in container returns the opposite Boolean result. Membership testing can also raise exceptions if an operation is unsupported or fails.
Membership is used in input validation, searching, filtering, duplicate detection and checking dictionary keys. It is not limited to lists and does not always require scanning every element.
1. Membership syntax and basic behavior#
PYTHONprint(3 in [1, 2, 3], 4 not in (1, 2, 3)) print('py' in 'python', '' in 'python')
Output:
True True
True TrueThe candidate appears on the left and the container or iterable on the right.
| Expression | Meaning |
|---|---|
x in values | Test whether values contains x |
x not in values | Test whether values does not contain x |
not (x in values) | Negate the membership result |
The empty string is a substring of every string, including the empty string. String membership checks contiguous substrings, not just whether each individual character appears somewhere.
The word in also appears in for-loop syntax and comprehensions. In those contexts it introduces an iterable; it is not itself performing a membership test.
2. Membership depends on the container#
| Container | What membership tests |
|---|---|
| list, tuple | Whether an element matches the candidate |
| str | Whether the candidate string is a substring |
| dict | Whether the candidate is a key |
| dict.keys() | Whether a key exists |
| dict.values() | Whether a value matches |
| dict.items() | Whether a matching key-value pair exists |
| set, frozenset | Whether an equal member exists |
| range | Whether a value belongs to the represented sequence |
| bytes, bytearray | An integer byte value or supported bytes-like subsequence |
| iterator | Whether a matching value is encountered during traversal |
| Custom container | Its defined containment protocol |
For a list of records, membership does not automatically search individual fields inside each record. Similarly, dictionary membership does not recursively search nested dictionaries.
3. Dictionary membership checks keys, not values#
PYTHONd = {'id': 7, 'name': 'Asha'} print('id' in d, 7 in d, 7 in d.values(), ('id', 7) in d.items())
Output:
True False True TrueThe dictionary has an 'id' key associated with the integer 7. Consequently, 'id' in d succeeds, but 7 in d does not.
Use d.values() when searching for a value and d.items() when testing a key-value association. Dictionary views reflect changes to the underlying dictionary.
Key membership is usually a better choice than checking d.get(key) when an existing key might store None. For example, a dictionary can contain a key associated with None, and get alone cannot distinguish that state from an absent key when its default is None.
Do not use membership testing as a substitute for an atomic database constraint or transaction. A check followed by a separate update can race with another operation.
4. Sets, ranges and efficient lookups#
PYTHONprint(5 in range(1, 10, 2), 6 in range(1, 10, 2)) print(1.0 in {1, 2}, 1.0 in range(3))
Output:
True False
True TrueThe first range represents 1, 3, 5, 7 and 9. The integer 5 belongs to it, but 6 does not.
For ordinary integer candidates, range membership uses the arithmetic structure of the range instead of enumerating every element. Other candidate types can use a different comparison path. In particular, an equal floating-point value can match an integer in a range.
Set membership is based on hashing and equality. Compatible numeric values such as 1 and 1.0 compare equal and have equal hashes, so the set containing integer 1 also contains a matching float value.
A set is useful for repeated membership queries, provided the values satisfy its hashability requirements. It is not necessarily a replacement for a sequence when order, duplicate occurrences or unhashable elements matter.
5. How Python resolves the membership protocol#
For a user-defined object, Python can resolve membership through __contains__, iteration or the older integer-indexed sequence protocol. These are type-level special-method protocols.
The diagram presents the usual protocol selection. An explicitly disabled protocol or an exception from a selected method may cause an error rather than allowing another fallback. A method that exists but fails is not automatically treated as a missing method.
When __contains__ is available, it determines the containment behavior. Otherwise, Python generally tries iteration. When the old sequence protocol is applicable, Python can request successive integer indexes beginning at zero until IndexError indicates exhaustion.
A successful element match during the ordinary fallback search stops traversal. The protocol can propagate other exceptions, including exceptions raised during iteration or equality comparison.
6. Custom containment with __contains__#
A container can implement membership without representing a finite collection of stored elements.
PYTHONclass ClosedInterval: def __init__(self, low, high): self.low, self.high = low, high def __contains__(self, value): return self.low <= value <= self.high window = ClosedInterval(10, 20) print(15 in window, 21 not in window)
Output:
True TrueThe class treats values within the inclusive numerical interval as members. It does not need to store every possible value in that interval.
The example assumes compatible comparable bounds and candidate values. A real interval class should validate its bounds and document whether endpoints are inclusive.
Membership expressions return Boolean results even if the custom method returns a non-Boolean value.
PYTHONclass NonBoolean: def __contains__(self, item): return [item] if item else [] print(1 in NonBoolean(), 0 not in NonBoolean())
Output:
True TrueThe nonempty list returned for 1 is truthy, while the empty list returned for 0 is falsy. Python truth-tests the result of __contains__. Returning a bool directly is generally the clearest implementation.
Custom containment may perform arbitrary work or raise exceptions. Its complexity is determined by its implementation rather than by the in keyword.
7. Iteration and legacy sequence fallback#
PYTHONclass Iterable: def __iter__(self): return iter([10, 20, 30]) class Indexed: def __getitem__(self, index): return (10, 20, 30)[index] print(20 in Iterable(), 99 in Indexed())
Output:
True FalseThe first object implements iteration but does not define __contains__. Python searches the supplied iterator. The second object provides integer indexing, and its tuple raises IndexError after the last valid position.
The legacy protocol is useful for understanding existing sequence-like classes. For new iterable classes, provide __iter__ explicitly when iteration is the intended interface. Define __contains__ separately when a specialized search or mathematical membership test is more appropriate.
A custom indexed sequence must signal exhaustion correctly. Returning values forever for increasing indexes can prevent an unsuccessful membership search from terminating.
8. Membership can consume an iterator#
PYTHONg = iter([1, 2, 3, 4]) print(2 in g, list(g)) g = iter([1, 2, 3]) print(9 in g, list(g))
Output:
True [3, 4]
False []The first test advances the iterator through the matching element 2, leaving 3 and 4 available. The second test traverses the entire iterator because the candidate is absent.
The important distinction is that a reusable collection can normally supply a fresh iterator, whereas an iterator itself retains its traversal position.
A search for a missing value in an infinite iterator may never finish. If multiple searches are needed, consider materializing a bounded input or building an appropriate index. Do not materialize an unbounded stream without an explicit stopping policy.
9. Element identity and equality#
For ordinary list membership, an element matches when it is the same object as the candidate or compares equal to it. The identity shortcut can produce behavior that differs from an explicit loop testing equality alone.
PYTHONn = float('nan') print(n == n, n in [n], float('nan') in [n])
Output:
False True FalseNaN does not compare equal to itself. However, the same NaN object is recognized as a member of the list containing that object. A separately created NaN is neither the same object nor equal to it.
This demonstrates why ordinary sequence membership cannot always be replaced by a generator expression using only ==. Container-specific behavior also matters: string membership, range optimizations and custom __contains__ methods need not perform an ordinary element-by-element identity-or-equality scan.
Hash-based containers additionally rely on hash values and their equality contract. Objects which compare equal must have equal hashes when they are hashable. A custom __eq__ method can also raise an exception or return an object that must be truth-tested during membership.
10. Bytes membership#
PYTHONprint(b'AB' in b'CABD', 65 in b'ABC', 256 not in range(256))
Output:
True True TrueBytes membership accepts suitable bytes-like subsequences as well as integer byte values from 0 through 255. The value 65 is the byte corresponding to ASCII A.
An out-of-range integer, such as 256 in b'ABC', raises ValueError rather than returning False. Text strings and binary byte sequences represent different kinds of data; use explicit encoding or decoding at the appropriate boundary.
11. Membership time complexity#
| Operation | Typical lookup cost |
|---|---|
| Candidate in list or tuple | O(n) worst-case element comparisons |
| Key in dictionary | Expected O(1) hash-table lookup |
| Value in dictionary values view | O(n) worst-case comparisons |
| Member in set or frozenset | Expected O(1) hash-table lookup |
| Ordinary integer in range | Independent of represented range length |
| Substring in string | Depends on substring lengths and implementation |
| Candidate in iterator | O(k) traversal steps to the first match, or until exhaustion |
| Candidate in custom container | Depends on its protocol implementation |
These are conventional complexity descriptions, not absolute timing guarantees. Hashing, collisions, equality methods, arbitrary-precision arithmetic and custom iterator work can alter actual costs. Dictionary and set lookups can degrade under collisions. Integer range membership can involve arithmetic on large integers.
Building a set from n hashable elements generally takes expected O(n) work and O(u) storage for u unique elements under ordinary hash-table assumptions. It can be worthwhile for many subsequent lookups, but creating a new set for a single test may cost more than a short list scan.
12. Practical example: validate supported file suffixes#
PYTHONallowed = {'csv', 'json'} def supported(filename): _, dot, suffix = filename.rpartition('.') return bool(dot) and suffix.casefold() in allowed print([supported(x) for x in ['report.CSV', 'data.json', 'image.png', 'README']])
Output:
[True, True, False, False]The function extracts the final suffix and checks membership in a small set. Case folding lets the example accept report.CSV without maintaining separate upper- and lowercase entries.
This is only a filename-suffix policy. It does not verify actual file contents, MIME type, path safety or whether a file is safe to process. Production upload validation requires appropriate content and security checks.
13. Practical example: filter records using a lookup set#
PYTHONwanted = {'A', 'C'} records = [('A', 10), ('B', 20), ('C', 30)] print([record for record in records if record[0] in wanted])
Output:
[('A', 10), ('C', 30)]Here membership is tested against a set of permitted identifiers, while the original records remain in their original iteration order.
For n records and m wanted identifiers, building the lookup set and filtering typically requires expected O(n + m) work under bounded-size hashing and equality assumptions. The additional storage includes the set and the filtered output. The technique is particularly useful when the same lookup set is reused for many records.
If duplicate identifiers in the wanted input carry meaning, converting them to a set discards that information. Choose the data structure according to the required behavior.
14. Common membership errors#
The following independent tests produced the indicated exceptions.
| Expression | Expected exception | Explanation |
|---|---|---|
1 in 42 | TypeError | Integer 42 does not provide a containment or iteration protocol |
[] in {1, 2} | TypeError | A list is unhashable |
1 in "123" | TypeError | Ordinary string membership requires a string candidate |
256 in b"ABC" | ValueError | The integer is outside the byte range |
Other common mistakes include checking dictionary values with key membership, forgetting that membership consumes an iterator, assuming set lookup is always constant-time and treating a successful membership test as proof that an object is safe or authorized.
Prefer a direct membership expression over redundant comparisons to True. For example, if key in mapping is generally clearer than if (key in mapping) == True.
Frequently asked questions#
What is the difference between in and not in?#
The in operator tests membership. The not in operator negates that result.
Can in search a string?#
Yes. For a string container, in checks whether the candidate string is a contiguous substring.
Does in search dictionary values?#
Not by default. It checks keys. Use mapping.values() to search values or mapping.items() to check key-value associations.
Is set membership faster than list membership?#
For sufficiently large collections and repeated lookups, a set often performs fewer comparisons because it uses hashing. Actual performance depends on workload, element types, construction costs and hash behavior.
Does membership work with generators?#
Yes, but a search consumes values up to the match or until exhaustion. A missing value in an infinite iterator may cause the search never to finish.
Can I customize the membership operator?#
Yes. Implement __contains__ on a suitable class to define containment. If the method is absent, Python can use iteration or the legacy sequence protocol.
Interview-ready answer#
The membership operators in Python are in and not in. They return a Boolean result indicating whether a candidate belongs to a container or iterable. Their meaning depends on the container: lists and tuples search elements, strings search substrings, dictionaries test keys, and sets use hashing and equality. Python supports custom containment through __contains__, with iteration and legacy sequence fallback when appropriate. Membership may consume iterators, and its complexity depends on the data structure and operation contract. Use the correct container and be aware of exceptions, hashability and iterator exhaustion.
Official references#
- Python Language Reference — Membership test operations
- Python Language Reference — Emulating container types
- Python Standard Library — Sequence Types
- Python Standard Library — Mapping Types
- Python Standard Library — Set Types
- Python Standard Library — Binary Sequence Types
- Python Standard Library — Iterator Types
Verification note: Eleven independent runnable examples and four expected-exception tests passed locally on CPython 3.13.5. The two fenced Mermaid diagrams were manually reviewed for protocol selection and iterator consumption. Mermaid parser and CLI were unavailable locally, so parser-level validation and public-site rendering remain unverified. Official reference links are supplied under the authorized offline research exception; live documentation and Supabase changelog were not checked.
References
- 1.Python Language Reference — Membership test operationsdocs.python.org
- 2.Python Language Reference — Emulating container typesdocs.python.org
- 3.Python Standard Library — Sequence Typesdocs.python.org
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design