Click for All Topics
To determine whether a value is a member of a sequence or collection in Python, we use the membership operators. They tell us whether an element is a member of a string, list, tuple, or set. Python offers’ in’ and ‘not in’ membership operators.
They provide an easy way to test membership and handle different cases based on the presence or absence of an element.
The ‘in’ operator in Python is used to check if a value exists as a member or element within a container or sequence. It returns true if the value is found in the container, and false if not.
edslash = ['python', 'M', 'Data science]
print('python' in edslash)
# Output of the above Python code:
# ---> True
print('java' in fruits)
# Output of the above Python code:
#---> False
Here we have a list named ‘edslash’ that contains elements named ‘python’, ‘ML’, and ‘Data science’.
When we apply the operator, we see that it returns true only for the elements that are present in the list.
The “not in” operator is used to check if a value does not exist as a member or element within a sequence. It returns true if the value is not found in the container, and false otherwise. Here is an example
edslash = ['python', 'M', 'Data science]
print('python' not in edslash)
# Output of the above Python code:
#---> False
print('java' not in edslash)
# Output of the above Python code:
#---> True
Article written by Aakarsh Pandey, Team edSlash
Office:- 660, Sector 14A, Vasundhara, Ghaziabad, Uttar Pradesh - 201012, India