Membership operators in Python
Membership operators in Python
Python provides membership operators to test for the presence of a value within a sequence (like strings, lists, tuples, or sets) or the presence of a key within a dictionary. These operators return a Boolean value (True or False).
There are two membership operators in Python:
in operator:
The in operator evaluates to True if the value on its left operand is found within the sequence or collection on its right operand.
Otherwise, it evaluates to False.
Python
x = ["apple", "banana"]
print("banana" in x)
Output
True
# returns True because a sequence with the value "banana" is in the list
Not in operator:
The not in operator evaluates to True if the value on its left operand is not found within the sequence or collection on its right operand.
Otherwise, it evaluates to False. This operator essentially provides the opposite result of the in operator.
Python
x = ["apple", "banana"]
print("pineapple" not in x)
Output
True
# returns True because a sequence with the value "pineapple" is not in the list
 
 
 
 
 
 
 

No comments: