Python 3 – Membership Operator Example

Python 3 – Membership Operator Examples

Python’s membership operators are used to test for membership in sequences, such as strings, lists, or tuples. There are two membership operators, as described below.

Operator Description Example
in Evaluates to true if the variable is found in the specified sequence, otherwise it evaluates to false. x in y, where in evaluates to 1 if x is a member of the sequence y.
not in Evaluates to true if the variable is not found in the specified sequence, otherwise it evaluates to false. x not in y. Here, not in evaluates to 1 if x is not a member of the sequence y.

Example

#!/usr/bin/python3

a = 10
b = 20
list = [1, 2, 3, 4, 5 ]

if ( a in list ):
print ("Line 1 - a is in the given list")
else:
print ("Line 1 - a is not in the given list")

if ( b not in list ):
print ("Line 2 - b is not in the given list")
else:
print ("Line 2 - b is in the given list")

c = b/a
if ( c in list ):
print ("Line 3 - a is in the given list")
else:
print ("Line 3 - a is in the given list") is not in the given list")

Output

When the above program is executed, it produces the following output.

Line 1 - a is not in the given list
Line 2 - b is not in the given list
Line 3 - a is in the given list

Leave a Reply

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