Alex Vincent
Alex Vincent

Reputation: 97

Python ID in same list not equal

x = [1,2,3]
y = x

print(id(x))
print(id(y))
print(id(x) == id(y))
print(id(x) is id(y))

Output:

140181905497736
140181905497736
True
False

Why is the second one false when the id of x and y are the same?

Upvotes: 1

Views: 384

Answers (2)

shish023
shish023

Reputation: 533

You see this because in the first comparison you compare the identities of the two objects but in the second you compare the two new objects generated by the id() function. This example you help you understand better:

# Here you can see that a and b are indeed the same
>>> a = [1,2,3]
>>> b = a
>>> a is b
True
>>> id(a) == id(b)
True

# Now lets store id(a) and id(b). Their values should still be the same
>>> A = id(a)
>>> A
4319687240
>>> B = id(b)
>>> B
4319687240
>>> A == B
True

# But A and B are separate objects. Which is what you compare in the second comparison 
>>> id(A)
4319750384
>>> id(B)
4319750544
>>> id(a) is id(b)
False
>>> A is B
False

# You can also see this at play if you try to print id of another id
>>> print(id(id(a)))
4319750416
>>> print(id(id(a)))
4319750512

Upvotes: 0

Chris_Rands
Chris_Rands

Reputation: 41168

when you do id(x) is id(y) you're comparing the identities of the object's integer identities and not of the list objects themselves. As an implementation detail integers are only cached in CPython in the range of -5 to 256. id(x) == id(y) does return True of course as expected because x is y returns True.

Upvotes: 1

Related Questions