Does python list store the object or the reference to the object?

删除回忆录丶 提交于 2021-02-16 04:29:30

问题


Size of an integer is 24 bytes and size of a char is 38 bytes, but when i insert into a list the size of the list doesn't reflect the exact size of the object that i insert. So, now I am wandering list is holding the reference of the object and the object is storing somewhere in memory.

>>> sys.getsizeof(1)
24
>>> sys.getsizeof('a')
38
>>> sys.getsizeof([])
72
>>> sys.getsizeof([1])
80
>>> sys.getsizeof(['a'])
80
>>> sys.getsizeof('james') 
42
>>>

回答1:


All values in Python are boxed, they don't map to machine types or sizes. Namely everything in the implementation of CPython is a PyObject struct.

http://docs.python.org/2/c-api/structures.html#PyObject

So, now I am wandering list is holding the reference of the object and the object is storing somewhere in memory.

A list is also a PyObject that contains a sequence of references to other PyObjects for the elements of the list. The list is allocated on the Python heap that is managed by the Python garbage collector.




回答2:


Everything in python is stored as reference. So your assumption is right.

>>> id(1)
10274744
>>> a = [1]
>>> id(a)
11037512
>>> id(a[0])
10274744
>>> sys.getsizeof(1)
24
>>> sys.getsizeof(a)
80

You see that the a[0] points to the id/address of 1. This shows that only the reference to the object is stored in the list.



来源:https://stackoverflow.com/questions/21178563/does-python-list-store-the-object-or-the-reference-to-the-object

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