Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
1 view
in Python by (580 points)
edited by

I want to know how to find the size of objects like string,integer etc in Python.

Currently, I am using an XML file which contains size fields that specify the size of value. I must parse this XML and do my coding. When I want to change the value of a particular field, I will check the size field of that value. Here I want to compare whether the new value that I'm going to enter is of the same size as in XML. I need to check the size of new value. In case of a string I can say its the length but in case of int, float, etc. I am confused.

1 Answer

0 votes
by (10.9k points)

You can use the sys.getsizeof() function from the sys module.

The sys.getsizeof(object[,default]) function returns the size of the object in bytes.The objects can be of any type and this function is implementation specific which means it will return correct results for built-in objects but for third-party extensions it may not be true.

 

Here, the default argument allows you to define a value which will be returned if the object does not provide means to retrieve the size , else a TypeEror may be raised.

 

The getsizeof() calls the _sizeof_ method of the object and adds extra garbage collector overhead in case, the garbage collector manages the object.

 

Ex-

 >>> import sys

>>> a = 2

>>> sys.getsizeof(a)

24

>>> sys.getsizeof(sys.getsizeof)

32

>>> sys.getsizeof('hello')

38

>>> sys.getsizeof('hello world')

48

 

Note:

getsizeof() function was introduced in Python 2.6 version.

If you are using an older version (lower than Python 2.6) then refer to this doc http://code.activestate.com/recipes/546530/ .

Hope this answer helps!

Related questions

0 votes
1 answer
asked Sep 17, 2019 in Python by Sammy (47.6k points)
+2 votes
3 answers
asked May 24, 2019 in Python by Suresh (3.4k points)
0 votes
1 answer

Browse Categories

...