Python
In this tutorial we will learn about Identity operators in Python.
We use the identity operator to check the memory locations of two objects.
Following are the identity operators in Python
is
operatorThis operator returns True if both the variables point at the same object.
In the following example we have two integer variables having same value and we are checking if they are identical.
# variables
x = 10
y = 10
result = x is y
print("result:", result)
We will get True
because both x and y are identical.
We can also check the id of the variables using the id()
function.
The id()
function returns a unique id for a given object.
Every object in Python gets a unique id when they are created.
The id of an object is an integer value that represents the address of an object in memory.
In the following example we are checking if the two variables are identical and also printing their id value.
# variables
x = 10
y = 10
result = x is y
print("result:", result, id(x), id(y))
The above code will give us a similar output as shown below.
result: True 4488129824 4488129824
is not
operatorThis operator returns True if both the variables does not point at the same object.
In the following example we have two variables having different values and we are checking if they are not identical.
# variables
x = 10
y = "Super"
result = x is not y
print("result:", result, id(x), id(y))
The above code will give a similar output.
result: True 4372065568 4374307928
We are getting True
because both x and y are not identical.
ADVERTISEMENT