Count Until Tuple

Tags: tuple

Write a Python program to count the elements in a tuple until an element is a tuple.

Example 1:

Input: (1, 2, 3, (1, 2), 4) 
Output: 3

Example 2:

Input: ('a', 'b', 'c', ('d', 'e'), 'f', 'g') 
Output: 3

Iterate over the tuple and increase a counter until you encounter an item of type tuple.

def count_until_tuple(t):
count = 0
for item in t:
if isinstance(item, tuple):
count += 1
return count

© Let’s Data Science


Unlock AI & Data Science treasures. Log in!