The **len()** function gives the length of the list or dictionary. I want to know the size of a python object, such as a list, dictionary, etc., in bytes. Is there any function for this?

+2 votes

You can use the **getsizeof()** function of the "sys" module. It returns the size of a python object in bytes. It works correctly for all built-in objects, but the returned size for the third-party extensions may not be correct.

Here is an example using the **getsizeof()** function:

>>> import random

>>> a=[random.randint(1,1000) for _ in range(1000)]

>>> len(a)

1000

>>> import sys>>> sys.getsizeof(a)

9016

To find the total bytes consumed by the elements of a Numpy array, you can also use the** nbytes** attribute. However, it will not include the memory consumed by non-element attributes of the array object.

E.g.

>>> import numpy as np

>>> a=np.random.random(10241024)>>> a.nbytes

81928192