Crus4

logo

What are Membership Operators in Python


Membership Operators in Python, are used to check if any specific item is present in a sequence (String, List etc.) or not. Python provides two membership operators: ‘in‘ operator & ‘not in‘ operator.

The operator ‘in‘ checks if the item is present in a sequence. If the item is present in a sequence it returns True, otherwise False. The ‘not operator‘ also checks if the item is present in a sequence. If the item is present in a sequence it returns False, otherwise it returns True.

Let’s write a code in an example below to clearly understand about Python Membership Operator.

Example

studts = ['John', 'Abdul', 'Ravi']
# Using 'in' operator
print('Ravi' in studts)   # Outputs: True
print('David' in studts)    # Outputs: False
# Using 'not in' operator
print('Sam' not in studts)   # Outputs: True
print('Abdul' not in studts)    # Outputs: False

Code Explanation

In an above code we first create a list of students (studts) and add three students in that list John, Abdul and Ravi. Then we use the ‘in’ operator to check if the student Ravi is present in a list or not. Since the student Ravi is present in a list, so it returns True. Similarly we check if the student David is present in a list, since it is not present in a list so it returns False.

Then we use the ‘not in‘ operator to check if the student Sam is present in a list, Since it is not present in a list so it returns True.


Share This Post!

What are Membership Operators in Python

One thought on “What are Membership Operators in Python

Leave a Reply

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