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
>>>
Do python lists store values or pointers? Python lists don't store values themselves. They store pointers to values stored elsewhere in memory. This allows lists to be mutable.
Python has a built-in module named 'array' which is similar to arrays in C or C++. In this container, the data is stored in a contiguous block of memory. Just like arrays in C or C++, these arrays only support one data type at a time, therefore it's not heterogenous like Python lists. The indexing is similar to lists.
Python list can hold a list of class objects. We can create one empty list and append multiple class objects to this list. Each list element will be an object, and we can access any member of that object like method, variables, etc. Note that you can append different class objects to the same list.
Yes, the order of elements in a python list is persistent.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With