use sys.getsizeof to determine the sizes in python

The sys.getsizeof() function returns the size of an object in bytes.

To use it, first import the sys module:

main.py
import sys
11 chars
2 lines

Then, you can use the getsizeof() function to determine the size of an object:

main.py
my_list = [1, 2, 3, 4, 5]
print(sys.getsizeof(my_list))  # output: 120
71 chars
3 lines

This will print out the size in bytes of the my_list object, which is a list containing five integers. Note that the actual size might be larger than what's printed, because Python reserves some memory for its internal use.

You can use this function to determine the size of other objects as well, such as dictionaries:

main.py
my_dict = {'a': 1, 'b': 2, 'c': 3}
print(sys.getsizeof(my_dict))  # output: 248
80 chars
3 lines

Again, the actual size might be larger than what's printed.

related categories

gistlibby LogSnag