问题
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