w3resource

Python Exercise: Count the elements in a list until an element is a tuple

Python tuple: Exercise-24 with Solution

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

Sample Solution:

Python Code:

# Create a list 'num' that contains a sequence of numbers and a tuple.
num = [10, 20, 30, (10, 20), 40]

# Initialize a counter 'ctr' to keep track of the index of the first tuple in the list.
ctr = 0

# Iterate through each element 'n' in the 'num' list.
for n in num:
    # Check if 'n' is an instance of a tuple.
    if isinstance(n, tuple):
        # If 'n' is a tuple, exit the loop.
        break
    # Increment the counter 'ctr' for non-tuple elements.
    ctr += 1

# Print the value of the 'ctr' variable, which represents the index of the first tuple in the list.
print(ctr) 

Sample Output:

3 

Flowchart:

Flowchart: Count the elements in a list until an element is a tuple

Python Code Editor:

Previous: Write a Python program to sort a tuple by its float element.
Next: Write a Python program convert a given string list to a tuple.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/tuple/python-tuple-exercise-24.php