a = 1
b = 1
id(a) == id(b)
a = 1.0
b = 1.0
id(a) != id(b)
why when a and b is decimal id(a) != id(b) in python ?
when number is decimal python will create two objects ?
a = 1
b = 1
id(a) == id(b)
a = 1.0
b = 1.0
id(a) != id(b)
why when a and b is decimal id(a) != id(b) in python ?
when number is decimal python will create two objects ?
The only reason why id(1) == id(1)
is that the low integers are cached for performance. Try id(1000) == id(1000)
Actually, sometimes that works. A better test allocates things in different statements:
>>> x = 1
>>> y = 1
>>> id(x) == id(y)
True
>>> x = 1000
>>> y = 1000
>>> id(x) == id(y)
False
>>>
>>> id(1000) == id(1000)
True
The same thing can happen with strings, as well, under even more conditions:
>>> x = 'abcdefg'
>>> y = 'abcdefg'
>>> x is y
True
The bottom line is that using is
(or comparing id()
values, which is essentially the same thing, but slower) to determine if two objects are identical is only a good strategy under certain circumstances, because Python will cache objects for performance.
One hard and fast rule is that two different mutable objects will have different id
values, but as the commenters below point out, there are no guarantees as to whether multiple immutable objects of the same value will or will not be created.
It is easier for the interpreter to cache things when you use literal values. If you make it calculate things, then you can see which things it works really hard to cache, vs. which things it opportunistically caches because it noticed them in proximity:
>>> x = 1000
>>> y = 2000 // 2
>>> x is y
False
>>> x == y
True
>>> x = 1
>>> y = 2 // 2
>>> x is y
True
>>>
>>> x = 'abcdefg'
>>> y = 'abcdefg'
>>> x is y
True
>>> y = 'abc' + 'defg'
>>> x is y
True
>>> x = 'abcdefghijklmnopqrstuvwxyz'
>>> y = 'abcdefghijklmnopqrstuvwxyz'
>>> x is y
True
>>> y = 'abcdefghijklm' + 'nopqrstuvwxyz'
>>> x is y
False
>>> x == y
True