0

I tested following in Windows 7 cmd:

Python 3.7.1 (v3.7.1:260ec2c36a, Oct 20 2018, 14:57:15) [MSC v.1915 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 8
>>> b = 8
>>> id(a)
8791373558832
>>> id(b)
8791373558832
>>> a is b
True
>>> c = -8
>>> d = -8
>>> id(c)
4802576
>>> id(d)
5223952
>>> c is d
False
>>> type(a)
<class 'int'>
>>> type(c)
<class 'int'>
>>>

Objects a, b, c, d are all of type int, I used to think the objects of the same type should be processed in the same way in memory allocation. I have search The Python Standard Library documentation but find nothing relative to this.

Could any one help to explain?

rustyhu
  • 1,912
  • 19
  • 28

1 Answers1

1

id and is are only really meaningful for mutable objects. If you have an immutable object, a value, then you should be using == instead of is (and I don't know what you're using id for but maybe you should look at hash instead). For objects that can't change there's no meaningful difference between values that share the same physical storage and values that don't. The runtime makes choices about when to share physical storage and when not to based on implementation concerns.

Jean-Paul Calderone
  • 47,755
  • 6
  • 94
  • 122
  • Sorry this is a late comment, I think I was using `id` for checking whether 2 objects were in fact the same object. I have been told somewhere that `id` in CPython implementation returns memory address of object, as I am more familiar with C++, using memory address to check seems quite right and meaningful. Thank you for your explaination and maybe I need to change my perspective to observe Python. – rustyhu Sep 23 '20 at 02:05