Python Membership operators are used to test if a sequence is presented in an object (such as strings, lists, or tuples).
Python programming has two membership operators as explained below:
Operator | Description | Example |
---|---|---|
in | Evaluates to true if it finds a variable in the specified sequence and false otherwise. | x in y, here in results in a 1 if x is a member of sequence y. |
not in | Evaluates to true if it does not finds a variable in the specified sequence and false otherwise. | x not in y, here not in results in a 1 if x is not a member of sequence y. |
Membership Operators in Python
Simple example code checks whether a sequence appears in an object or not.
a = 10
b = 20
list1 = [1, 2, 3, 4, 5]
if a in list1:
print("a is available in the given list1")
else:
print("a is not available in the given list1")
if b not in list1:
print("b is not available in the given list1")
else:
print("b is available in the given list1")
a = 2
if a in list1:
print("a is available in the given list1")
else:
print("La is not available in the given list1")
Output:
You can also use membership operators with strings:
# Using 'in' operator with strings
my_string = "Hello, World!"
if 'o' in my_string:
print("'o' is in the string")
# Using 'not in' operator with strings
if 'x' not in my_string:
print("'x' is not in the string")
This prints “‘o’ is in the string” because the character ‘o’ is present in the string, and it prints “‘x’ is not in the string” because the character ‘x’ is not present in the string.
Membership operators are very useful for testing membership in collections and sequences, which is a common operation in Python programming.
These operators are often used in conditional statements and loops to check the presence or absence of elements in sequences. They are particularly useful when working with collections like lists, tuples, sets, and strings.
Comment if you have any doubts or suggestions on this Python operator topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.