Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Get the memory size of a variable using sys.getsizeof() - Python Program

To obtain the memory size of a variable in Python using sys.getsizeof(), the sys module must first be imported. Then, the sys.getsizeof() function can be called, passing the variable as an argument. The function returns the size of the object in bytes. 

It is important to note that sys.getsizeof() provides the size of the object itself, including its internal structure and overhead, but it does not recursively account for the memory consumed by objects that the variable might reference (e.g., elements within a list or values within a dictionary). 

 

import sys # Integer variable a = 10 print(f"Size of a: {sys.getsizeof(a)} bytes") # String variable b = "Hello, Python!" print(f"Size of b: {sys.getsizeof(b)} bytes") # List variable c = [1, 2, 3, "a", "b"] print(f"Size of c: {sys.getsizeof(c)} bytes") # Dictionary variable d = {"key1": "value1", "key2": 123} print(f"Size of d: {sys.getsizeof(d)} bytes")

Output

 
OUTPUT  :
Size of a: 28 bytes
Size of b: 55 bytes
Size of c: 104 bytes
Size of d: 184 bytes