This article explains how to write a Python Program to find tuple length with examples. There are multiple options for finding the length of a tuple; the built-in len() function is the best approach. However, native approaches use a for loop or a while loop. Along with them, we can use the enumerate() function, reduce(), etc to find the tuple length.
Python Program to find the length of a tuple using len()
As we all know, the built-in tuple len() function is the most effective way of finding the tuple length. It accepts a tuple object as the parameter value and counts the total number of items. The syntax of the tuple len() function is
len(tuple)
As you can see, it accepts a tuple of any data type (single or mixed) and counts the total number of items and returns the tuple length as output.
In this example, we declared a tuple of five integer items. Next, used the built-in Python tuple len() function to find the length of a tuple of integers. The print() statement displays the total number of tuple items returned by the len() function. Here, we can assign the result to an extra variable for further calculations.
t = (10, 20, 30, 40, 50)
print(len(t))
5
Python len() function to find the length of a tuple of strings
Similar to the integers, we can use the tuple len() function on a tuple of strings to find the length. It will consider each string (word) as one item and count the total number of tuple items. In the example below, we declared a tuple of three strings (fruits) and used the len() function to calculate the length.
t = ('apple', 'Mango', 'kiwi')
print(len(t))
3
How to find the length of the longest tuple in Python?
When working with a tuple of strings, there are situations where we have to find the length of the longest word (string) in a tuple. In such a case, we must use the built-in max() function along with a key argument. Next, set that key argument value to the len() function.
t = ("Milk", "Mile Bread", "Cheese Cake", "Ice Cream")
val = max(t, key = len)
print(val)
As you can see from the below, the length of the Cheese Cake is 11, which is the longest word in a tuple of strings.
Cheese Cake
How to find the length of each tuple item in Python?
Similar to the above, we can use the len() function to find the length of each tuple item. For this, we must use the for loop to iterate over the tuple items. On each iteration, we must use the tuple len() function to find the length of a single tuple item.
t = ("Milk", "Mile Bread", "Cheese Cake", "Ice Cream")
for ch in t:
print(ch, len(ch))
As you see, on each iteration, it reads the tuple item (string) and the tuple len() function calculates the length of the string.
Milk 4
Mile Bread 10
Cheese Cake 11
Ice Cream 9
How to find the length of an empty tuple in Python?
As we all know, the tuple len() function counts the total number of items in a given tuple from start to end. If it is an empty tuple, there would be no items to count, so the len() function returns 0 as the length for an empty tuple.
t = ()
print(len(t))
0
Python Program to Find the Length of a Tuple of Mixed Items
As we mentioned earlier, the len() function returns the length of a tuple irrespective of the data types it holds. To demonstrate, in this example, we declared a nested and mixed tuple.
By default, the len() function counts each item, whether it is a single item or a nested tuple, as one. So, when you use the len() function on nested tuples, it will treat the nested tuple as one item and return the length. However, if you want the nested tuple length, you have to use that nested item’s index position. For instance, len(mTuple[4]) returns the length of a nested tuple (1, 2, 3, 4).
mTuple = ('Apple', 22, 'Kiwi', 45.6, (1, 2, 3, 4), 16, [10, 30, 70])
print("Mixed Tuple Items = ", mTuple)
mtupleLength = len(mTuple)
print("Mixed Tuple Length = ", mtupleLength)
nestedtupleLength = len(mTuple[4])
print("Nested Tuple Length = ", nestedtupleLength)
nestedlistLength = len(mTuple[6])
print("List Nested inside a Tuple Length = ", nestedlistLength)

How to find the total length of a nested tuple in Python?
In the above example, we have mentioned that we can use the index position to get the length of an individual nested tuple. However, if you want the total length or total number of items in a tuple (including the nested items), we must use the for loop.
Here, the for loop iterates over the list items, and each item is a nested tuple. Within the loop, the len() function calculates the length of the nested tuple at that position, and the count value updates the set length.
t = ((12, 22), (32, 42, 52), (62, 72, 82))
print("Length =",len(t))
count = 0
for i in t:
count += len(i)
print("Total Items =",count)
Length = 3
Total Items = 8
Python Program to find the length of a user-defined tuple
In this Program, we declared an empty tuple. Next, we use the for loop to allow the user to enter the tuple items. Next, the arithmetic + operator adds those elements into the empty tuple. Next, the built-in len() function finds the length of the user-defined tuple.
s = ()
number = int(input("Enter the Total Tuple Items = "))
for i in range(1, number + 1):
value = int(input("Enter the %d value = " % i))
s += (value,)
print("Tuple Items = ", s)
ln = len(s)
print("Tuple Length = ", ln)
Enter the Total Tuple Items = 4
Enter the 1 value = 22
Enter the 2 value = 99
Enter the 3 value = 128
Enter the 4 value = 65
Tuple Items = (22, 99, 128, 65)
Tuple Length = 4
Alternative ways to find the length of a tuple in Python
Apart from the built-in len() function, we can use a native approach of using a for loop or a while loop to calculate the tuple length. In real-time, we use the len() function; for interview purposes, it is better to understand the alternatives.
Python Program to find tuple length using a for loop
Using a for loop is one of the most popular ways to calculate the tuple length, and this native approach gives a complete idea. In the example below, we declared an integer tuple of six elements.
The for loop iterates over the list items from the start to the end. On each iteration, the count value is increased by 1. At the end of a for loop, the count variable contains the total number of elements in a tuple, which is its length.
t = (10, 20, 30, 40, 50, 60)
count = 0
for _ in t:
count += 1
print(count)
6
Using enumerate()
Unlike the for loop, we don’t have to declare and increment the counter variable in the enumerate() function to calculate the tuple length in Python. By default, enumerate() access index position and the tuple value at that position. So, all we have to do is use the enumerate() to iterate over the tuple items and use pass to do nothing. Next, print the index value as the output because it consist the tuple’s last index position (last item).
Remember to assign 1 as the second argument of the enumerate() function because the default index position value is 0, so set it to 1 to get the tuple. Otherwise, add one to the output.
t = ("Milk", "Bread", "Cheese", "Butter", "Ice Cream")
for count, _ in enumerate(t, 1):
pass
print(count)
5
Using sum() and a generator expression
In the following example, the generator expression creates a sequence of 1’s for each tuple item. Next, the sum() function calculates the sum of those 1’s, which is the tuple length in Python.
t = ("Milk", "Cheese", "Butter")
count = sum(1 for _ in t)
print(count)
3
Python Program to find tuple length using a while loop
There are multiple options to find the tuple length using a while loop. In this example, we declared an integer list of seven items. As the while loop is always True and it leads to an infinite loop, we use try catch block to stop looping infinite times. On each while loop iteration, t[count] accesses one tuple time, and the next line increments the count value by 1.
Once there are no items to read from a tuple, it will raise an IndexError. We use the except to catch it and exit the loop. As the count variable has the total number of tuple items (tuple length), print that value.
t = (1, 3, 6, 9, 12, 15, 17)
count = 0
try:
while True:
t[count]
count += 1
except IndexError:
pass
print(count)
7
Similar to the above Python tuple length program, we can use the iter() function to convert the given tuple to an iterator object. On each iteration of the while loop, use the next() function to read the next tuple item and increment the count value. Once there are no tuple items, catch the StopIteration and execute the break statement to exit the loop.
t = (1, 3, 6, 9, 12, 15, 17)
count = 0
it = iter(t)
while True:
try:
next(it)
count += 1
except StopIteration:
break
print(count)
7
Python Program to find tuple length using recursion
Apart from the regular while loop or for loop, we can use the recursive function concept to find the tuple length. Unlike the looping techniques, the recursive function repeatedly calls the function with an updated tuple value.
In the example below, it will recursively call the tupleLength function for each item in a given tuple. On each call, the slicing technique removes the first item from a tuple.
def tupleLength(n):
if n == ():
return 0
else:
return 1 + tupleLength(n[1:])
t = (2, 4, 6, 8, 10)
print(tupleLength(t))
5
Using reduce() function
Along with the len() function, there is a reduce() function in the functools library to find the tuple length.
In the example below, the reduce() function sets its starting value to 0 and moves from the tuple’s starting point to the end. Here, the lambda expression adds (accumulates) one for each tuple item. As the tuple items finish, the Python reduce() function has the total number of tuple items, and the print() displays the length.
from functools import reduce
t = ("Milk", "Cheese", "Butter", "Ice Cream")
count = reduce(lambda x, _: x + 1, t, 0)
print(count)
4
Using map() and sum() functions
In the following example, the map() function iterates over the items in a tuple. The lambda expression assigns 1 for each tuple item. In the ned, it creates a map object with a sequence of 1’s. The sum() function calculates the sum of those 1’s, which is the tuple length.
t = (2, 3, 6, 12, 20, 19, 80)
count = sum(map(lambda x: 1, t))
print(count)
7
Using the __len__()
Although the Python tuple len() function internally calls the __len__() method to calculate the tuple length, do not use it in real-time. The example below shows usage, and it is not recommended for use.
t = (2, 3, 6, 12, 20, 19, 80)
count = t.__len__()
print(count)
7