What is Membership Operators(in , not in) in Python?
Python is one of the most in-demand programming languages in the market today. The not operator in Python is a part of the Membership Operators in Python. A Membership Operator in Python can be defined as being an operator that is used to validate the membership of a value. This operator is used to test memberships in variables such as strings, integers as well as tuples.
- In Operator: The in operator in Python is used to check if the value exists in a variable or not. When evaluated, if the operator finds a value then it returns true otherwise false. To understand this better, take a look at the example below.
# Python program to illustrate
# Finding common member in list
# using 'in' operator
list1=[1,2,3,4,5]
list2=[6,7,8,9]
for item in list1:
if item in list2:
print("overlapping")
else:
print("not overlapping")
Output:
not overlapping
- Not In Operator: This operator is the exact opposite of the in operator. When evaluated this operator returns true if the value isn’t found and false if the value is found. Take a look at the example below to understand this better.
# Python program to illustrate
# not 'in' operator
x = 24
y = 20
list = [10, 20, 30, 40, 50 ];
if ( x not in list ):
print ("x is NOT present in given list")
else:
print ("x is present in given list")
if ( y in list ):
print ("y is present in given list")
else:
print ("y is NOT present in given list")
Output:
x is NOT present in given list
y is present in given list