Check if a value exists within a sequence
Membership operators are used to test whether a value is present in a sequence (like a list, tuple, set, string, or dictionary).
Operator | Description | Example |
---|---|---|
in |
Returns True if a value is found in the sequence | 'a' in 'apple' → True |
not in |
Returns True if a value is NOT found in the sequence | 5 not in [1, 2, 3] → True |
# Strings
word = "hello"
print("h" in word) # True
print("z" not in word) # True
# Lists
fruits = ["apple", "banana", "cherry"]
print("apple" in fruits) # True
print("grape" not in fruits) # True
# Tuples
nums = (1, 2, 3)
print(2 in nums) # True
# Sets
letters = {'a', 'b', 'c'}
print('d' in letters) # False
# Dictionaries (checks keys)
info = {"name": "John", "age": 55}
print("name" in info) # True
print("John" in info.values()) # True
in
to simplify conditional logic.in
on dictionaries when checking for keys, use .values()
or .items()
to check values or key-value pairs.not in
to filter or validate inputs cleanly.banned_words = {"bad", "ugly", "hate"}
comment = "I hate this product!"
if any(word in comment.lower() for word in banned_words):
print("Comment contains inappropriate content!")