Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How much space does each element of a list take?

I need a very large list, and am trying to figure out how big I can make it so that it still fits in 1-2GB of RAM. I am using the CPython implementation, on 64 bit (x86_64).

Edit: thanks to bua's answer, I have filled in some of the more concrete answers.

What is the space (memory) usage of (in bytes):

  • the list itself
    • sys.getsizeof([]) == 72
  • each list entry (not including the data)
    • sys.getsizeof([0, 1, 2, 3]) == 104, so 8 bytes overhead per entry.
  • the data if it is an integer
    • sys.getsizeof(2**62) == 24 (but varies according to integer size)
    • sys.getsizeof(2**63) == 40
    • sys.getsizeof(2**128) == 48
    • sys.getsizeof(2**256) == 66
  • the data if it is an object (sizeof(Pyobject) I guess))
    • sys.getsizeof(C()) == 72 (C is an empty user-space object)

If you can share more general data about the observed sizes, that would be great. For example:

  • Are there special cases (I think immutable values might be shared, so maybe a list of bools doesn't take any extra space for the data)?
  • Perhaps small lists take X bytes overhead but large lists take Y bytes overhead?
like image 426
Paul Biggar Avatar asked Nov 05 '09 13:11

Paul Biggar


People also ask

How much space does a list take in Python?

When you create a list object, the list object by itself takes 64 bytes of memory, and each item adds 8 bytes of memory to the size of the list because of references to other objects.

How many bytes does a list of 1000000 integers take in Python?

What makes an integer in Python. Since a small integer uses 28 bytes, now we know why a million integers take 28MB of RAM. But why do Python integers take so much memory? Every object in the default Python implementation, CPython, is also a PyObject C struct or one of its variants.

How many bytes is a list in Python?

This is only the space required to store the list structure itself (which is an array of pointers to the Python objects for each element). A 32-bit system will require 4 bytes per element, a 64-bit system will use 8 bytes per element.

How do you find the memory size of a list?

In order to determine the size of the list, we have passed the list object to the getsizeof() function which on execution return the sizes of list1 and list2 in bytes along with garbage collector overhead. List1 and list2 are occupying 112 bytes and 104 bytes in the memory.


1 Answers

point to start:

>>> import sys
>>> a=list()
>>> type(a)
<type 'list'>
>>> sys.getsizeof(a)
36
>>> b=1
>>> type(b)
<type 'int'>
>>> sys.getsizeof(b)
12

and from python help:

>>> help(sys.getsizeof)
Help on built-in function getsizeof in module sys:

getsizeof(...)
    getsizeof(object, default) -> int

    Return the size of object in bytes.
like image 51
bua Avatar answered Oct 23 '22 14:10

bua