How to Check the Memory Size of a List in Python?

Estimated read time 1 min read

To check the memory size of a list in Python, you can use the sys.getsizeof() function from the built-in sys module. Here’s an example code snippet that demonstrates this approach:

import sys

my_list = [1, 2, 3, 4, 5]
size_in_bytes = sys.getsizeof(my_list)

print("Memory size of my_list:", size_in_bytes, "bytes")

In this code, we first import the sys module. We then create a sample list my_list containing some elements. We can use the sys.getsizeof() function to get the memory size of this list in bytes and store it in the variable size_in_bytes.

Finally, we print the memory size of the list using the print() function.

Note that the sys.getsizeof() function only returns the memory size of the list object itself and does not include the memory usage of the objects contained within the list. If the list contains other objects (e.g., other lists, dictionaries, or custom objects), you may need to recursively calculate their memory sizes and add them to the total size of the list.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply