Home »
Python »
Python Programs
Python program to find the size of a tuple
Size of a tuple in Python: In this tutorial, we will learn how to find the size of a tuple (number of elements) in Python programming language?
Submitted by Shivang Yadav, on June 05, 2021
Python programming language is a high-level and object-oriented programming language. Python is an easy to learn, powerful high-level programming language. It has a simple but effective approach to object-oriented programming.
Tuples in Python is a collection of items similar to list with the difference that it is ordered and immutable.
Example:
tuple = ("python", "includehelp", 43, 54.23)
Find the size of a tuple using len() method
We can find the size (the number of elements present) for a tuple easily using the built-in method present in the Python's library for collection, the len() method.
Syntax
len(tuple_name)
The method accepts a collection as input and returns the number of elements present in it.
Program to find the size of tuple in Python
# Python program to find the size of a tuple
# Creating a tuple in python
myTuple = ('includehelp', 'python', 3, 2021)
# Finding size of tuple using len() method
tupleLength = len(myTuple)
# Printing the tuple and Length
print("Tuple : ", str(myTuple))
print("Tuple Length : ", tupleLength)
Output:
Tuple : ('includehelp', 'python', 3, 2021)
Tuple Length : 4
Find the size occupied by the tuple in memory
In Python, we can also find the total amount of memory occupied by the tuple in Pusing the __sizeof__() method or getsizeof() method.
Find the size of a tuple using __sizeof__() method
__sizeof__() is a built0in method in python which is used to find the total memory space occupied by the object.
Syntax
object_name.__sizeof__()
It returns the space occupied by the object in bytes.
Program to find the size of tuple
# Python program to find the size of a tuple
# Creating a tuple in python
myTuple = ('includehelp', 'python', 3, 2021)
# Finding size of tuple
tupleSize = myTuple.__sizeof__()
# Printing the tuple and size
print("Tuple : ", str(myTuple))
print("Tuple Length : ", tupleSize)
Output:
Tuple : ('includehelp', 'python', 3, 2021)
Tuple Length : 56
Find the size of a tuple using getsizeof() method
Another method to find the amount of memory occupied by the object in Python is using getsizeof() method. The method is present in the sys module in Python.
Imported using: import sys
Syntax
sys.getsizeof(tuple_name)
Program to find the size of tuple in Python
# Python program to find the size of a tuple
import sys
# Creating a tuple in python
myTuple = ('includehelp', 'python', 3, 2021)
# Finding size of tuple
tupleSize = sys.getsizeof(myTuple)
# Printing the tuple and size
print("Tuple : ", str(myTuple))
print("Tuple Length : ", tupleSize)
Output:
Tuple : ('includehelp', 'python', 3, 2021)
Tuple Length : 80
Python Tuple Programs »