Language: EN

python-operadores-identidad

Identity Operators in Python

Identity operators in Python allow us to verify if two variables refer to the same object in memory. These operators are useful for comparing the identity of objects (that is, if two variables point to the same location in memory).

The is and is not operators are very efficient as they simply compare the memory addresses of two objects (they do not perform any additional operation).

OperatorNameDescription
isIsChecks if two variables point to the same object
is notIs notChecks if two variables do not point to the same object

List of identity operators

is Operator

The is operator is used to check if two variables refer to the same object in memory.

a = [1, 2, 3]
b = a

is_equal = (a is b)  # True, since a and b refer to the same object

In this example, both a and b point to the same object in memory, so the expression a is b is True.

is not Operator

The is not operator is used to check if two variables do NOT refer to the same object in memory.

x = 10
y = 10

is_not_equal = (x is not y)  # False, since x and y refer to the same object

In this example, both x and y point to the same object in memory (in Python, small integers are stored in the same location), so the expression x is not y is False.

Usage examples

Variable identity verification

x = 100
y = x

are_equal = (x is y)  # True, since x and y are the same object in memory

List identity verification

list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = list1

are_equal = (list1 is list2)  # False, since list1 and list2 are not the same object
are_equal2 = (list1 is list3)  # True, since list1 and list3 are the same object

Object identity verification

class MyClass:
    pass

object1 = MyClass()
object2 = MyClass()
object3 = object1

are_equal = (object1 is object2)  # False, since object1 and object2 are not the same object
are_equal2 = (object1 is object3)  # True, since object1 and object3 are the same object