Program to find the size of Tuple using Python

Introduction

The task is to find the size of tuple i.e. the memory size (in bytes) occupied by the tuple objects.

Program to find the size of Tuple using Python

Program

Approach 1

import sys 
ip_tuple1 = ('Demo 1', 1 ,'Demo 2', 2, "Demo 3", 3)
ip_tuple2 = ((1, "Ram"), (2, "Sita"), (3, "Gita"), (4, "Raj"))
# Using getsizeof()
print("The size of given tuple is : "+ str(sys.getsizeof(ip_tuple1)) + "bytes")
print("The size of given tuple is : "+ str(sys.getsizeof(ip_tuple2)) + "bytes")

Output:

Program to find the size of Tuple using Python Output 1

Approach 2

ip_tuple1 = ('Demo 1', 1 ,'Demo 2', 2, "Demo 3", 3)
ip_tuple2 = ((1, "Ram"), (2, "Sita"), (3, "Gita"), (4, "Raj"))
# Using _sizeof_()
print("The size of given tuple is : "+ str(ip_tuple1._sizeof_()) + "bytes")
print("The size of given tuple is : "+ str(ip_tuple2._sizeof_()) + "bytes")

Output

Program to find the size of Tuple using Python Output 2 

Explanation

In the above python code, we have created two tuples with some entries. In approach 1 we have used getsizeof() function on both the input tuples to calculate the size of tuple whereas in approach 2 we have used _sizeof_() function.

From output we can observe that the calculated size returned by getsizeof() function is greater than that of the size returned by _sizeof_() function. The reason is getsizeof() function returns the output including the garbage collector overhead memory.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.