The Python sys.getsizeof() method returns the size, in bytes of a Python object. This includes the object's contents and overhead. It is primarily used for memory profiling and debugging to understand how much memory an object consumes.
This method takes one argument, the object whose size is to be measured and an optional default argument to return if the object doesn't support size retrieval.
We have to note that sys.getsizeof() method doesn't account for the sizes of referenced objects only the immediate size of the given object.Syntax
Following is the syntax and parameters of Python sys.getsizeof() method −
sys.getsizeof(object[, default])Parameters
Following are the parameters of the python sys.getsizeof() method −
This method returns the size of the object in bytes
Example 1Following is the example shows the size of an integer, a float and a string −
import sys x = 42 y = 3.14 s = "Hello, Welcome to Tutorialspoint!" print(sys.getsizeof(x)) print(sys.getsizeof(y)) print(sys.getsizeof(s))Output
28 24 82
Note: The exact size may vary depending on the Python implementation and platform.
Example 2This example shows the size of a list before and after adding an element. The size increases as elements are added due to the list's dynamic array structure −
import sys lst = [1, 2, 3, 4, 5] print(sys.getsizeof(lst)) # Adding element to list lst.append(6) print(sys.getsizeof(lst))Output
104 104Example 3
This example shows the size of a custom object. The sys.getsizeof() method only provides the size of the object itself not the size of objects it references −
import sys class MyClass: def __init__(self): self.x = 1 self.y = [1, 2, 3] obj = MyClass() print(sys.getsizeof(obj))Output
56Example 4
This example specifies a default size value to return if the object does not provide size information −
import sys class MyClass: def __init__(self): self.x = 1 # Default size if no size information is available print(sys.getsizeof(MyClass, default=100))Output
1072
python_modules.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4