Reputation: 43
I am aware that in python, integers from -5 to 256 can have the same ID. However, what are the consequences in the case where two immutable objects have the same ID? How about the consequences when two mutable objects have the same ID?
Thank you.
Upvotes: 1
Views: 189
Reputation: 1841
When two mutable objects have the same ID, they reference the same memory address.
a = 10
b = 10
print(id(a), id(b))
Output:
4355009952 4355009952
The only consequence of two mutable objects having the same ID is changing the value in one object will be reflected on the other.
a = 10
b = a
print(a, b)
print(id(a), id(b))
a = 6
print(a, b)
print(id(a), id(b))
Output:
10 10
4338298272 4338298272
6 10
4338298144 4338298272
Immutable objects having the same is not a consequence as they are immutable
Upvotes: 0
Reputation: 155353
An id
is definitionally unique at a given point in time (only one object can have a given id
at once). If you see the same id
on two names at the same time, it means it's two names referring to the same object. There are no "consequences" to this for immutable types like int
, because it's impossible to modify the object through either alias (x = y = 5
aliases both x
and y
to the same 5
object, but x += 1
is roughly equivalent to x = x + 1
for immutable objects, rebinding x
to a new object, 6
, not modifying the 5
object in place); that's why optimizations like the small int
cache you've observed are safe.
Upvotes: 5