How many bytes per element are there in a Python list (tuple)?

后端 未结 5 1900
醉酒成梦
醉酒成梦 2020-12-02 23:47

For example, how much memory is required to store a list of one million (32-bit) integers?

alist = range(1000000) # or list(range(1000000)) in Python 3.0
         


        
5条回答
  •  有刺的猬
    2020-12-03 00:40

    A new function, getsizeof(), takes a Python object and returns the amount of memory used by the object, measured in bytes. Built-in objects return correct results; third-party extensions may not, but can define a __sizeof__() method to return the object’s size.

    kveretennicov@nosignal:~/py/r26rc2$ ./python
    Python 2.6rc2 (r26rc2:66712, Sep  2 2008, 13:11:55) 
    [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
    >>> import sys
    >>> sys.getsizeof(range(1000000))
    4000032
    >>> sys.getsizeof(tuple(range(1000000)))
    4000024
    

    Obviously returned numbers don't include memory consumed by contained objects (sys.getsizeof(1) == 12).

提交回复
热议问题