Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

list

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
>>>
like image 949
James Avatar asked Jan 17 '14 05:01

James


People also ask

Do Python list store values or pointers?

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.

How does Python list store data?

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.

Can Python lists hold objects?

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.

Does a list keep its order Python?

Yes, the order of elements in a python list is persistent.


2 Answers

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.

like image 189
Stephen Diehl Avatar answered Sep 25 '22 18:09

Stephen Diehl


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.

like image 22
Aswin Murugesh Avatar answered Sep 28 '22 18:09

Aswin Murugesh