Why two individually created immutable objects have same id and mutable objects have different while both refer to same values? [duplicate]

拥有回忆 提交于 2019-12-18 08:46:34

问题


Two individually created mutable list have different ids.

Python SHELL: (mutable)

>>> mylist = ['spam', 'eggs']
>>> yourlist = ['spam', 'eggs']
>>> id(mylist), id(yourlist)
(49624456, 48910408)

While two individually created immutable strings have similar ids.

Python SHELL: (immutable)

>>> a = 10
>>> b = 10
>>> id(a), id(b)
(507099072, 507099072)

Is a and b referencing to a same object? If no, why ids are similar? Is mylist and yourlist referencing to different objects? If yes, why they have different ids.


回答1:


Python caches some small strings and numbers: http://docs.python.org/2/c-api/int.html#PyInt_FromLong

The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object.

And id(some_list) always gives you the address of container - list object in memory, not strings in list!



来源:https://stackoverflow.com/questions/21091568/why-two-individually-created-immutable-objects-have-same-id-and-mutable-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!