In Python, these data types are all represented as objects. Each object occupies a certain amount of space in memory, and the size of an object can vary. This tutorial will show how to get the size of an object in Python using the getsizeof() function. Follow the below for more information.
Get the Size of an Object in Python
To get the size of an object in Python, first, we need to import the sys module in Python. Then we can use the getsizeof() function, which attributes in the sys module, to get the size of an object in Python. Pass in the object as an argument to the function, and it will return the size of an object in bytes. This method works for all built-in objects.
You can see the syntax of this function below.
The getsizeof() function
sys.getsizeof(data)
Parameters
- data: The data is a list, dict, tuple …
Get the size of a list
First, we need to import sys module. Then we will create a list to get the size of this list. Final, we can use the getsizeof() function to get the size of this list as follows.
# Import the sys module import sys # Create a list lstNumber = [2, 5, 7, 8] # Get the size of a list in bytes resultSize = sys.getsizeof(lstNumber) # View a result print("The size of the list is:", resultSize)
Output
The size of the list is: 120
Get the size of a tuple
Here, we will get the size of a tuple similar to a list. Check out the code example below.
# Import the sys module import sys # Create a tuple myTup = ('S', 'h', 'a', 'r', 'e', 'I', 'T') # Get the size of a tuple in bytes resultSize = sys.getsizeof(myTup) # View a result print("The size of the tuple is:", resultSize)
Output
The size of the tuple is: 96
Get the size of a number, string, dictionary, etc
In addition, we will determine the size of an integer, dictionary, etc. Consider the following example:
# Import the sys module import sys # Get the size of an interger number in bytes print(sys.getsizeof(5)) # Get the size of a float number in bytes print(sys.getsizeof(12.6)) # Get the size of a string in bytes print(sys.getsizeof('ShareIT')) # Get the size of a set in bytes print(sys.getsizeof({6, 8, 9, 3})) # Get the size of a dictionary in bytes print(sys.getsizeof({1: 'b', 2: 'd', 3: 'a', 4: 'e'}))
Output
28
24
56
216
232
Summary
This tutorial demonstrated how to get the size of an object using the getsizeof() function and the sys module in Python. If you have any questions or would like further clarification, please leave a comment below.
Have a great day!

Hi, guys! My name’s Scott Miller. My current job is a software developer and I have shared a lot of quality articles about Javascript, C, C++, C#, Python, PHP, R, Java programming languages. I’m hoping they can assist you.
Name of the university: HCMUS
Major: IT
Programming Languages: C, C++, Python, R, Java, JavaScript