Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

Python: Get the size of an object in bytes

Python Basic: Exercise-79 with Solution

Write a Python program to get the size of an object in bytes.

Pictorial Presentation:

Get the size of an object in bytes

Sample Solution:

Python Code:

import sys
str1 = "one"
str2 = "four"
str3 = "three"
x = 0
y = 112
z = 122.56
print("Size of ",str1,"=",str(sys.getsizeof(str1))+ " bytes")
print("Size of ",str2,"=",str(sys.getsizeof(str2))+ " bytes")
print("Size of ",str3,"=",str(sys.getsizeof(str3))+ " bytes")
print("Size of",x,"=",str(sys.getsizeof(x))+ " bytes")
print("Size of" ,y,"="+str(sys.getsizeof(y))+ " bytes")
L = [1, 2, 3, 'Red', 'Black']
print("Size of",L,"=",sys.getsizeof(L)," bytes")
T = ("Red", [8, 4, 6], (1, 2, 3))
print("Size of",T,"=",sys.getsizeof(T)," bytes")
S = {'apple', 'orange', 'apple', 'pear'}
print("Size of",S,"=",sys.getsizeof(S)," bytes")
D = {'Name': 'David', 'Age': 6, 'Class': 'First'}
print("Size of",D,"=",sys.getsizeof(S)," bytes")

Sample Output:

Size of  one = 52 bytes
Size of  four = 53 bytes
Size of  three = 54 bytes
Size of 0 = 24 bytes
Size of 112 =28 bytes
Size of [1, 2, 3, 'Red', 'Black'] = 104  bytes
Size of ('Red', [8, 4, 6], (1, 2, 3)) = 72  bytes
Size of {'orange', 'pear', 'apple'} = 224  bytes
Size of {'Name': 'David', 'Age': 6, 'Class': 'First'} = 224  bytes

Python Code Editor:

 

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to find the available built-in modules.
Next: Write a Python program to get the current value of the recursion limit.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Python: Tips of the Day

Find current directory and file's directory:

To get the full path to the directory a Python file is contained in, write this in that file:

import os 
dir_path = os.path.dirname(os.path.realpath(__file__))

(Note that the incantation above won't work if you've already used os.chdir() to change your current working directory, since the value of the __file__ constant is relative to the current working directory and is not changed by an os.chdir() call.)

To get the current working directory use

import os
cwd = os.getcwd()

Documentation references for the modules, constants and functions used above:

  • The os and os.path modules.
  • The __file__ constant
  • os.path.realpath(path) (returns "the canonical path of the specified filename, eliminating any symbolic links encountered in the path")
  • os.path.dirname(path) (returns "the directory name of pathname path")
  • os.getcwd() (returns "a string representing the current working directory")
  • os.chdir(path) ("change the current working directory to path")

Ref: https://bit.ly/3fy0R6m