Python Membership Operator

Membership Operator

The membership operator is also a special operator and is used to check if a certain object is a member of the given collection or not i.e. it a member of the list, set or a collection of characters or not.

Example:

>>>lis1= [1, 2, 3] #creating a list
>>>print(1 in lis1)
>>>print(5 in lis1)
>>>print(4 not in lis1)

Output:

True #checking 1 as a member
False #checking 5 as a member
True #checking 4 not as a member

Here we create a list lis1 with elements 1, 2 and 3. To check if the particular element is present in the list or not we use the ‘in’ special operator. First, we check if 1 is in the list or not. Then we check for 5. The output is then True and false respectively. We then check if 4 is ‘not in’ the list and the output for this is True since 4 is not an element in the string.

Note: ‘is’ and ‘is not’ are identity operators whereas ‘in’ and ‘not in’ are membership operators in Python.

Example:

>>>str= “Hello World”
>>>print(“Hello” in str)
>>>print(“W” in str)
>>>print(“hi” in str)
>>>print(“W” not in str)

Output:

True #output for checking hello
True #output for checking W
False #output for checking hi
False #output for checking if W is not in the string

We take a string str in this example as “Hello World” and then first check if “Hello” is present or not then similarly for ‘W’ and ‘hi’. The output is True, True and False respectively since ‘Hello’ and ‘W’ are present in the string str and ‘hi’ is not. We then check if “W” is ‘not in’ the string str and the answer is false as it is present.

Note: It is case sensitive thus the upper case and lower case characters are treated differently. For instance, a character ‘L’ and ‘l’ will be checked for separately.

We can also check for blank spaces using the membership operator.

Example:

>>>str= “Hello World”
>>>print(“ ” in str)

Output: True

Here we check if the blank space is present in the string str or not. Since it is present therefore the output is True.

It checks for the first instance of the character and even if it is present multiple times it only gives the output as True once.

Leave a Comment

Your email address will not be published. Required fields are marked *