Python Membership Operators
```mermaid title=“how in decides, and why it means different things per type” desc=“The operator is a protocol, not a search. Python asks the container first, and only falls back to iterating and comparing if the container has no opinion. That is why the same keyword means substring for a string, key for a dictionary, and element for a list — each type answers the question its own way.”
flowchart TD
A[“x in obj”] —> Bdoes obj define __contains__?
B —>|yes| C[“obj.contains(x) decides”]
B —>|no| Dis obj iterable?
D —>|yes| E[“iterate, compare with == , stop at the first match”]
D —>|no| F[“TypeError: argument of type … is not iterable”]
C —> G[“str: SUBSTRING test”]
C —> H[“dict: tests KEYS, not values”]
C —> I[“set / dict: hash lookup, O(1)”]
E —> J[“list / tuple: linear scan, O(n)”]
:::caution[The same keyword, three different questions]
Verified:
| Expression | Result | What was tested |
| --- | --- | --- |
| `'ell' in 'hello'` | `True` | **substring** — not a character |
| `'h' in 'hello'` | `True` | also a substring, of length 1 |
| `1 in {1: 'a'}` | `True` | the **key** |
| `'a' in {1: 'a'}` | **`False`** | values are not searched |
| `2 in Iter()` | `True` | no `__contains__`, so it iterated and compared |
The dictionary row is the one that bites. `value in some_dict` looks like a containment check on
the data and is a check on the keys — use `in some_dict.values()` if you meant the values, and
be aware that is a linear scan rather than a hash lookup.
The string row matters when a variable might be a single character or a longer piece of text:
`user_input in "yesno"` is `True` for `"yes"`, `"no"`, `"es"`, and `""`. That is rarely the test
anyone intended.
:::
## Exploring Membership Operators in Python
Membership operators in Python are fundamental tools for checking whether a value is a member of a sequence, such as a string, list, or tuple. These operators, in and not in, provide a concise and expressive way to validate the presence or absence of an element within a collection. In this comprehensive guide, we'll delve into the world of membership operators, their syntax, and their applications in Python programming.
:::note
Membership operators are also known as inclusion operators.
:::
The following table lists the membership operators in Python:
| Operator | Description | Example |
| :--- | :--- | :--- |
| `in` | Returns `True` if a sequence with the specified value is present in the object | `x in y` |
| `not in` | Returns `True` if a sequence with the specified value is not present in the object | `x not in y` |
## in Operator
#### `in` Operator
The `in` operator returns `True` if a sequence with the specified value is present in the object. The following example demonstrates how to use the `in` operator in Python:
```python title="operators.py" showLineNumbers{1} {4-5}
# in operator
x = 10
y = 5
z = x in y
t = x in 10
print(z)
print(t)Output:
C:\Users\Your Name> python operators.py
False
TrueIn the above example, we have used the in operator to check if the value of x is present in the object y. Since the value of x is not present in the object y, the condition becomes False. The result of the in operator is then assigned to the variable z. The value of z is then printed to the console.
not in Operator
Section titled “not in Operator”not in Operator
Section titled “not in Operator”The not in operator returns True if a sequence with the specified value is not present in the object. The following example demonstrates how to use the not in operator in Python:
# not in operator
x = 10
y = 5
z = x not in y
t = x not in 10
print(z)
print(t)Output:
C:\Users\Your Name> python operators.py
True
FalseIn the above example, we have used the not in operator to check if the value of x is not present in the object y. Since the value of x is not present in the object y, the condition becomes True. The result of the not in operator is then assigned to the variable z. The value of z is then printed to the console.
Membership Operators with Lists
Section titled “Membership Operators with Lists”The membership operators can be used with lists. The following example demonstrates how to use the membership operators with lists in Python:
# Membership operators with lists
x = [1, 2, 3, 4, 5]
y = 10
z = y in x
t = y not in x
print(z)
print(t)Output:
C:\Users\Your Name> python operators.py
False
TrueIn the above example, we have used the membership operators with lists. The in operator returns True if the value of y is present in the list x. Since the value of y is not present in the list x, the condition becomes False. The not in operator returns True if the value of y is not present in the list x. Since the value of y is not present in the list x, the condition becomes True.
Conclusion
Section titled “Conclusion”Membership operators in Python are powerful tools for validating the presence or absence of values within sequences. Whether you’re working with lists, tuples, strings, or sets, in and not in provide a concise and readable syntax for membership testing.
As you advance in your Python programming journey, experiment with membership operators, incorporate them into your conditional statements, and explore their applications in real-world scenarios. For more insights and practical examples, check out our tutorials on Python Central Hub!
Check yourself
Section titled “Check yourself”-
What does `'a' in {1: 'a'}` return?
Verified. `in` on a dict tests keys. `'a' in d.values()` is the values check — and that one is a linear scan rather than a hash lookup.
pch.quizShowAnswer
B — `False` — `in` tests keys, not values — Verified. `in` on a dict tests keys. `'a' in d.values()` is the values check — and that one is a linear scan rather than a hash lookup.
-
`user_input in 'yesno'` — for which inputs is this True?
`in` on a string is a SUBSTRING test, and every string contains the empty string. That is almost never the check anyone intended.
pch.quizShowAnswer
B — 'yes', 'no', 'es', and the empty string — `in` on a string is a SUBSTRING test, and every string contains the empty string. That is almost never the check anyone intended.
-
A class defines no `__contains__` but is iterable. What does `x in obj` do?
Verified with a class defining only `__iter__` — the fallback found the value. That is why `in` works on any iterable, and why it costs a full scan when there is no hash.
pch.quizShowAnswer
C — Iterates and compares with `==`, stopping at the first match — Verified with a class defining only `__iter__` — the fallback found the value. That is why `in` works on any iterable, and why it costs a full scan when there is no hash.
-
Why is `x in some_set` so much cheaper than `x in some_list` for large collections?
A set lookup is roughly constant time; a list is linear. Measured elsewhere in this course at about 23,000x for 100,000 absent-value lookups.
pch.quizShowAnswer
B — A set hashes the value and looks in one bucket, rather than scanning — A set lookup is roughly constant time; a list is linear. Measured elsewhere in this course at about 23,000x for 100,000 absent-value lookups.
Try it: Membership Operators Exercises
Section titled “Try it: Membership Operators Exercises”Exercise 1 – in with a List
Section titled “Exercise 1 – in with a List”Exercise 2 – not in
Section titled “Exercise 2 – not in”Exercise 3 – in with a String
Section titled “Exercise 3 – in with a String”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading