Determine the size of an object in Python
This tutorial will give us a piece of extraordinary information about finding the memory size of an object in Python.
How to determine the size of an object in Python:
The memory size of an object in Python can determine by using a built-in function in Python,
And that is getsizeof()
. For this function, we have to import the system library.
We can import the system as import sys
Example:
import sys s1="hiii" s2="hello" s3="bye" print("The memory size of '"+s1+"' = "+str(sys.getsizeof(s1))+" bytes") print("Memory size of '"+s2+"' = "+str(sys.getsizeof(s2))+" bytes") print("The Memory size of '"+s3+"' = "+str(sys.getsizeof(s3))+" bytes")
Output:
The memory size of 'hiii' = 53 bytes Memory size of 'hello' = 54 bytes The Memory size of 'bye' = 52 bytes
Explanation:
From the above example, we can understand that s1,s2, and s3 are three objects containing some data.
And the memory sizes of each object did find by using sys.getsizeof()
And we got the sizes of each object as 53 bytes for ‘s1’ and 54 bytes for ‘s2’ and 52 bytes for s3 respectively.
We are using str()
in print function for converting the sizes as strings.
Leave a Reply