Find the size of a list – Python
In Python, a list is a collection data type that can store elements in an ordered manner and can also have duplicate elements. The size of a list means the amount of memory (in bytes) occupied by a list object. In this article, we will learn various ways to get the size of a python list.
getsizeof() function belongs to the python’s sys module. It has been implemented in the below example.
Size of list1: 96bytes Size of list1: 88bytes Size of list1: 112bytes
sys.getsizeof() function includes the marginal space usage, which includes the garbage collection overhead for the object. Meaning it returns the total space occupied by the object in addition to the garbage collection overhead for the spaces being used.
Python also has an inbuilt __sizeof__() method to determine the space allocation of an object without any additional garbage value. It has been implemented in the below example.
Size of list1: 72bytes Size of list1: 64bytes Size of list1: 88bytes
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course