Identity operators in python
Table of Contents
Introduction
Identity operators compare the memory location of two objects. There are two keywords to compare the memory location of an object; is and is not.
Before that, it is important to know about the id() function which is used to check the memory address of the object. For example, let’s declare a variable num1 which stores some integer value;
>>> num1 = 34
>>> id(num1)
140710077979328
So, to check the memory address of num1, we have to use the id() function and pass the object name as an argument. In our case, it returned some value (140710077979328) which is the memory address of num1 in the python namespace.
Now, let’s look into identity operators in python;
is
Evaluates to True if the objects on either side of the operator point to the same memory address and False otherwise.
Example:
>>> num1 = 4
>>> num2 = 6
>>> num3 = 10-4 # value will be 6
>>> num1 is num2
False
>>> num2 is num3 # Memory address of num2 and num3 is same
True
>>> id(num1) # Memory address of num1
140710077978368
>>> id(num2) # Memory address of num2
140710077978432
>>> id(num3) # Memory address of num3
140710077978432
is not
Evaluates to True if the objects on either side of the operator do not point to the same memory address and False otherwise.
Example:
>>> num1 = 4
>>> num2 = 6
>>> num3 = 10-4
>>> num1 is not num2 # Memory address of num1 and num2 is different
True
>>> num2 is not num3
False
>>> id(num1) # Memory address of num1
140710077978368
>>> id(num2) # Memory address of num2
140710077978432
>>> id(num3) # Memory address of num3
140710077978432
Other operators in python you must know:
- Arithmetic Operators
- Comparison Operators
- Assignment Operators
- Logical Operators
- Bitwise Operators
- Membership Operators
- Identity Operators