Python | Count the elements in a list until an element is a Tuple

In this problem, we need to accept a list. The list can have nested tuples. We need to count the elements in a list until a tuple has been encountered.

Examples:

Input : [4, 5, 6, 10, (1, 2, 3), 11, 2, 4]
Output : 4

Input : [4, (5, 6), 10, (1, 2, 3), 11, 2, 4]
Output : 1



In this program we will use the concept of isinstance() to verify whether we are encountering a tuple or not in our path of count. For detailed guide on isinstance() visit isinstance in Python.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to count the items
# until a list is encountered
def Count(li):
    counter = 0
    for num in li:
        if isinstance(num, tuple):
            break
        counter = counter + 1
    return counter
  
# Driver Code
li = [4, 5, 6, 10, (1, 2, 3), 11, 2, 4]
print(Count(li))

chevron_right


Output:

4


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.