Membership Operators

Python Membership Operators are used to test whether a value is found within a sequence or not. You can use a membership operator with list, string, tuple, set etc, to check a value whether it's present in the sequence or not.

There are two types of membership operators in python, are listed below :-

  • in
  • not in

in  Operator

Python in Operator is used to test if a value is found in a sequence or not. It will return True if value found within a sequence else it will return False. Let us understand this through a bunch of code -

let's take a list sequence first :-

list1=[10,20,30,45,'code']
print( 10 in list1)
print('code' in list1)
print( 40 in list1)
print(25 in list1)
print(20 in list1)

The output of the above code will be :-

True
True
False
False
True

Because as we can see that 10, ‘code’ and 20 are found  within a sequence, so the operator returns True.

In case of String sequence :-

st = "Hello Codiens"
print("codiens" in st)   # line 1
print("Codiens" in st)   # line 2

So, the output will be False and True, as we can see that the “codiens” in the first line are written in lower case while in string st, "Codiens"  are in capitalized form.

So, the first line will be false and second will be True.

False 
True

not in Operator

Python not in Operator is used to test if a value is found within a sequence or not. If the value  doesn’t appear in the sequence then it will return True, else it will return False.

For example :-

st = "Hello Coders"
print("coders" not in st)
print("Hello" not in st)

So, the output will be True and False, as we can see that the string "coders" doesn’t appear within a sequence then the first one is True and second string “Hello” is found within a sequence then it will be False.