Membership operators are used to check whether a value or variable is found in a sequence (such as a string
, list
, or tuple
). They are used to check if a value is present in a list or not.
in
: Returns True
if the value is found in the sequencenot in
: Returns True
if the value is not found in the sequencein
operatorx = [1, 2, 3]
print(1 in x) # Output: True
print(5 in x) # Output: False
not in
operatorx = [1, 2, 3]
print(1 not in x) # Output: False
print(5 not in x) # Output: True
In the above examples, the in
operator returns True
if the value is present in the list
, and False
if it is not. The not in
operator works in the opposite way, returning True
if the value is not present in the list, and False
if it is.
in
operator with strings
x = 'Hello World'
print('H' in x) # Output: True
print('z' in x) # Output: False
The membership operators can also be used to check if a particular character is present in a string
or not.
It is important to note that these operators work on any type of sequence in python such as strings
, lists
, and tuples
.
In summary, Membership Operators are used to check if a value is present in a sequence or not. They are very useful for checking if an item exists in a list or not and can also be used with strings to check if a particular character is present in a string or not.