Q:

Python program to count all the elements till first tuple

belongs to collection: Python Tuple Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

# Python program to count all 
# the elements till first tuple

# Initializing and printing tuple 
myTuple = (4, 6, (1, 2, 3), 7, 9, (5, 2))
print("The elements of tuple are " + str(myTuple))

# Counting all elements till first Tuple 
for count, ele in enumerate(myTuple):
	if isinstance(ele, tuple):
		break

print("The count of elements before first tuple is " + str(count))

Output:

The elements of tuple are (4, 6, (1, 2, 3), 7, 9, (5, 2))
The count of elements before first tuple is 2

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.

# Python program to count all 
# the elements till first tuple

from itertools import takewhile

# Initializing and printing tuple 
myTuple = (4, 6, (1, 2, 3), 7, 9, (5, 2))
print("The elements of tuple are " + str(myTuple))

# Counting all elements till first Tuple 
count = sum(1 for sub in takewhile(lambda val: not isinstance(val, tuple), myTuple))

print("The count of elements before first tuple is " + str(count))

Output:

The elements of tuple are (4, 6, (1, 2, 3), 7, 9, (5, 2))
The count of elements before first tuple is 2

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Tuple Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to perform the addition of nested t... >>
<< Python program to convert tuple to adjacent pair d...