Membership and Identity Operator in Python

In this tutorial, we will learn about Membership and Identity operator in Python 3.x earlier. This operator comes handy while using conditionals and looping constructs.

Membership Operators in Python

Membership operators are used to establish membership with a value. It tests for membership in an array, such as strings, lists, or tuples.

  1. in operator: The ‘in’ operator is used to enquire whether a value exists in an array or not. It Evaluates to be true if it finds a variable in the specified array and false otherwise.
  2. ‘not in’ operator- It works totally opposite to that of in operator. It checks for the availability of variable in the specified sequence and evaluates to be true if it does not find a variable in the specified sequence and false otherwise.
Return type: Boolean(True & False)

Now let’s take a look at the examples,

a = 10
b = 4
l1 = [1,2,3,4,5]
print a not in l1
print b in l1
Output:
True
False

Identity operators in Python

They are used to detect whether the value is of a certain class or type. They are generally used to determine the datatype of certain variable contains.
There are different identity operators such as

  1. The ‘is’ operator – It evaluates to be True if the variables on either side of the operator to the same object and false in every other case.
  2. The ‘is not’ operator – This is totally opposite to that of is operator.It evaluates to false if the variables on both side of the operator refer to the same object and true in every other case.
                Return type : Boolean(True & False)

Now lets discuss some illustrations,

x = "code speedy"
if (type(x) is str): 
    print ("This is a string") 
else: 
    print ("This is not a string") 
y=21
if (type(y) is not str): 
    print ("This is a string") 
else: 
    print ("This is not a string")
Output:
This is a string
This is not string

Also, learn,

Leave a Reply

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