Python program to Find the size of a Tuple



When it is required to find the size of a tuple, the ‘sizeof’ method can be used.

Below is the demonstration of the same −

Example

 Live Demo

import sys tuple_1 = ("A", 1, "B", 2, "C", 3) tuple_2 = ("Java", "Lee", "Code", "Mark", "John") tuple_3 = ((1, "Bill"), ( 2, "Ant"), (3, "Fox"), (4, "Cheetah")) print("The first tuple is :") print(tuple_1) print("The second tuple is :") print(tuple_2) print("The third tuple is :") print(tuple_3) print("Size of first tuple is : " + str(sys.getsizeof(tuple_1)) + " bytes") print("Size of second tuple is : " + str(sys.getsizeof(tuple_2)) + " bytes") print("Size of third tuple is: " + str(sys.getsizeof(tuple_3)) + " bytes")

Output

The first tuple is : ('A', 1, 'B', 2, 'C', 3) The second tuple is : ('Java', 'Lee', 'Code', 'Mark', 'John') The third tuple is : ((1, 'Bill'), (2, 'Ant'), (3, 'Fox'), (4, 'Cheetah')) Size of first tuple is : 96 bytes Size of second tuple is : 88 bytes Size of third tuple is : 80 bytes

Explanation

  • The required packages are imported.

  • The tuples are defined, and are displayed on the console.

  • The ‘sizeof’ method is called on every tuple and the length is displayed as output on the console.

Updated on: 2021-04-17T12:54:22+05:30

376 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements