Membership Operators in Python
What Are Membership Operators? Membership operators are used to test whether a value or variable is found in a sequence (like a string, list, tuple, or dictionary).
They return a Boolean value (True or False).
Types of Membership Operators
| Operator | Description | Example |
|---|---|---|
| in | Returns True if the value is present in the sequence | 'a' in 'apple' → ✅ True |
| not in | Returns True if the value is not present in the sequence | 'z' not in 'apple' → ✅ True |
Syntax
element in sequence element not in sequence
Example: Using with Strings.
Python
# Check if a character exists in a string
text = "Python Programming"
print('P' in text) # True → 'P' is present
print('z' in text) # False → 'z' is not present
print('thon' in text) # True → substring 'thon' is present
print('code' not in text) # True → 'code' is not present Example: Using with Lists.
Python
# Check if an element exists in a list
fruits = ['apple', 'banana', 'mango']
print('apple' in fruits) # True → 'apple' is present
print('grapes' in fruits) # False → not present
print('banana' not in fruits) # False → because 'banana' is present Example: Using with Tuples.
Python
numbers = (1, 2, 3, 4, 5) print(3 in numbers) # True print(10 not in numbers) # True
Example: Using with Dictionaries. In dictionaries:
• Membership operators check only the keys (not values).
Python
person = {'name': 'Ashish', 'age': 28, 'country': 'India'}
print('name' in person) # True → key exists
print('Ashish' in person) # False → values are not checked
print('salary' not in person) # True → key doesn't exist If we want to check values, you can use .values():
print('Ashish' in person.values()) # True