Python Membership Operators Example

Advertisements


Following table shows all the membership operators supported by Python language.

OperatorDescriptionExample
inEvaluates 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 inEvaluates 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 a member of sequence y.

Example:

Try following example to understand all the membership operators available in Python programming language:

#!/usr/bin/python

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

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

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

a = 2
if ( a in list ):
   print "Line 3 - a is available in the given list"
else:
   print "Line 3 - a is not available in the given list"

When you execute the above program it produces the following result:

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


Advertisements
Advertisements