10.2. Identity of objects

Python provides 2 different operators for assessing the equality of objects. The fisrt one: == generally tests that the values are equal, whereas the second one tests whether the 2 objects are the same object, i.e whether they are identical. In other words, the is operator looks if their memory locations are the same, whereas the == operator rather does a content based comparison. Therefore for simple objects, such as integers, and immutable objects, such as strings, the operators return the same result, but their behavior is different for composed objects such as lists and dictionaries. The following listing shows some examples:

>>> 10.0 == 10
True
>>> 10.0 is 10
False
>>> 10 is 10
True
>>> 10.0 is 10.0
True

>>> "atg" == "atg"
True
>>> "atg" is "atg"
True
>>> start = "atg"
>>> end = start
>>> start == end
True

>>> L1 = [1, 2, 3]
>>> L1 == [1, 2, 3]
True
>>> L1 is [1, 2, 3]
False
>>> L2 = L1
>>> L1 is L2
True
>>> L3 = L1[:]
>>> L1 is L3
False

>>> [1, [2, 3]] == [1, 2, 3]
False
>>> [1, [2, 3]] == [1, [2, 3]]
True
  

Figure 10.4 shows a representation to illustrate the examples of list comparisons done above.

Figure 10.4. List comparison

Identity of objects. In Python all objects have an identifier that is unique for each object. Therefore two objects are the same in the sense of is if they have the same identifier. You can ask for the identifier of an object in Python using the id function:

>>> id(10)
1104200
>>> id(10.0)
1424356

>>> id("atg")
1183232
>>> id(start)
1183232

>>> id(L1)
1177744
>>> id(L2)
1177744
>>> id(L3)
1121328
>>> id([1, 2, 3])
1174048
      

Warning

In Python strings are immutable and handled as identical i.e the same in the sense of the is function if they contain the same sequence of characters, but this is not the case in all programming languages. In C for example, even strings with the same sequence of characters can have different memory locations.