Python - Membership Operators
Membership operators are used to check the membership of an element in a sequence like lists, tuple etc. Python supports two membership operators:
- in - Returns true if a given element is present in the object.
- not in - Returns true if a given element is not present in the object
Example: in operator
In the example below, the in operator is used to check the presence of given element in a sequence. It can also be used to print content of a sequence.
MyList = [10, 20, 30, 40] MyTuple = ("Red", "Blue", "Green") #checking if MyList contains 40 if 40 in MyList: print("MyList contains 40.") else: print("MyList does not contain 40.") #checking if MyTuple contains "White" if "White" in MyTuple: print("MyTuple contains 'White'.") else: print("MyTuple does not contain 'White'.") #printing all content of MyList print("MyList contains:", end=" ") for i in MyList: print(i , end =" ")
The output of the above code will be:
MyList contains 40. MyTuple does not contain 'White'. MyList contains: 10 20 30 40
Example: not in operator
In the example below, the not in operator is used to check the presence of a given element in a given sequence.
MyList = [10, 20, 30, 40] MyTuple = ("Red", "Blue", "Green") #checking if MyList contains 40 if 40 not in MyList: print("MyList does not contain 40.") else: print("MyList contain 40.") #checking if MyTuple contains "White" if "White" not in MyTuple: print("MyTuple does not contain 'White'.") else: print("MyTuple contains 'White'.")
The output of the above code will be:
MyList contain 40. MyTuple does not contain 'White'.
❮ Python - Operators