How do I determine the size of an object in Python?

How do I determine the size of an object in Python?

Asked on November 8, 2018 in Python.
Add Comment


  • 3 Answer(s)

      For numpy arrays, getsizeof doesn’t work:

    from pylab import *
    from sys import getsizeof
    A = rand(10)
    B = rand(10000)
    

      Then (in ipython):

    In [64]: getsizeof(A)
    Out[64]: 40
    In [65]: getsizeof(B)
    Out[65]: 40
    

      Happily, though:

    In [66]: A.nbytes
    Out[66]: 80
    In [67]: B.nbytes
    Out[67]: 80000
    
    Answered on November 8, 2018.
    Add Comment
      Try this code:
    >>> import sys
    >>> x = 2
    >>> sys.getsizeof(x)
    24
    >>> sys.getsizeof(sys.getsizeof)
    32
    >>> sys.getsizeof('this')
    38
    >>> sys.getsizeof('this also')
    48
    
    

      If you are in python < 2.6 and don't have sys.getsizeof ,then use this extensive module instead.
    Answered on November 8, 2018.
    Add Comment

       Now is a rapid script I wrote constructed on the previous answers to list sizes of all variables:

    for i in dir():
        print (i, sys.getsizeof(eval(i)) )
    
    Answered on November 8, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.