Example:
tuple = ("python", "includehelp", 43, 54.23)
Counting all the elements till first Tuple
In the program, we are given a nested collection consisting of a tuple. And we need to create a Python program to count all the elements till the first tuple is encountered.
Input:
(4, 6, (1, 2, 3), 7, 9, (5, 2))
Output:
2
For this, we will traverse the collection till the first tuple is encountered. And count the new number of elements till the tuple. This can be done in Python using a combination of different methods.
Method 1:
One method to solve the problem is by looping over the collection using enumerate() which also returns the count and breaks the loop when a tuple is encountered checked using isinstance() method. The returned counter value of the enumerate() method is the required value.
Output:
Method 2:
Another method to solve the problem is by using a combination of takewhile() and sum method. The takewhile() method takes a lambda function to check if the element is not a tuple.
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer