1
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 ?

Pegasus
  • 1,398
  • 15
  • 20

1 Answers1

8

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
Patrick Maupin
  • 8,024
  • 2
  • 23
  • 42
  • Same idea as with `Integer.valueOf(1)` in Java. – Thilo Aug 13 '15 at 02:29
  • yes, but a = 1000, b = 1000, id(a) == id(b) is False. when i run "id(1000) == id(1000)" in shell is always true. – Pegasus Aug 13 '15 at 02:32
  • @Pegasus. Either way, the exact behaviour is very likely implementation-dependent and not mandated by the language spec. As a programmer, you must not depend on getting the same (or a different) object instance here. – Thilo Aug 13 '15 at 02:33
  • so is `id(1.0) == id(1.0)` , it also gives true. – Anand S Kumar Aug 13 '15 at 02:36
  • 2
    As an example, `id(1000) == id(1000)` returns False for me in IronPython 2.9.0.0-- which is fine, because no one ever promised otherwise. Note that in many implementations (but not ironpy, obviously!) objects generated by literals in the same statement may be reused. – DSM Aug 13 '15 at 02:38