Membership operators allow us to check if a value is present within a sequence, such as a string, list, tuple, or a set.
List of membership operators
Operator in
The in
operator is used to check if a value is present in a sequence.
fruits = ["apple", "banana", "cherry"]
is_banana = "banana" in fruits # True
is_grape = "grape" in fruits # False
In this example, we are checking if "banana"
is present in the fruits
list, which is True
. We also check if "grape"
is present, which is False
.
Operator not in
The not in
operator is used to check if a value is NOT present in a sequence.
fruits = ["apple", "banana", "cherry"]
is_not_grape = "grape" not in fruits # True
is_not_apple = "apple" not in fruits # False
In this example, we are checking if "grape"
is NOT present in the fruits
list, which is True
. We also check if "apple"
is NOT present, which is False
.
Usage Examples
Checking elements in a list
colors = ["red", "green", "blue"]
is_blue = "blue" in colors # True
is_not_yellow = "yellow" not in colors # True
Checking characters in a string
name = "John"
has_a = "a" in name # True
does_not_have_z = "z" not in name # True
Checking elements in a set
vowels = {"a", "e", "i", "o", "u"}
is_a_vowel = "a" in vowels # True
is_not_y = "y" not in vowels # True