Language: EN

python-operadores-pertenencia

Membership Operators in Python

Membership operators in Python allow us to check if a value is present within a sequence (such as a string, list, tuple, or set).

OperatorNameDescription
inInReturns True if the value is found in the sequence
not inNot inReturns True if the value is not found in the sequence

List of membership operators

in Operator

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.

not in Operator

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 = "Luis"

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