A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/python-count-elements-list-element-tuple/ below:

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

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

Last Updated : 14 Jan, 2025

The problem involves a list of elements, we need to count how many elements appear before the first occurrence of a tuple. If no tuple is found in the list, return the total number of elements in the list. To solve this, initialize a counter and use a while loop to iterate through the list, checking for a tuple with isinstance(). Return the count of elements before the first tuple or the length of the list if no tuple is found.

Using a for-loop with isinstance()

for loop iterates over each element in the list and isinstance() checks if the element is not a tuple. The sum() function counts all non-tuple elements until the first tuple is encountered.

Python
a = [1, 2, 3, (4, 5), 6, 7]

c = 0
for element in a:
    if isinstance(element, tuple):
        break
    c += 1

print(c)  

Explanation

Using enumerate() and any()

Using enumerate(), we iterate through the list with both the index and value. next() Function retrieves the index of the first tuple by checking each element with isinstance() and if no tuple is found, it defaults to the length of the list.

Python
a = [1, 2, 3, (4, 5), 6, 7]

c = next((i for i, x in enumerate(a) if isinstance(x, tuple)), len(a))

print(c)  

Explanation

Using a while-loop

Using a while loop, you can iterate through the list, checking each element with isinstance() until a tuple is encountered. The loop increments a counter and once a tuple is found, the iteration stops, providing the count of elements before the tuple.

Python
a = [1, 2, 3, (4, 5), 6, 7]

c = 0
while c < len(a) and not isinstance(a[c], tuple):
    c += 1

print(c) 

Explanation



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4