Python program to count the elements in a list until an element is a Tuple?


In this article, we will count the elements in a list until an element is a Tuple.

The list is the most versatile datatype available in Python, which can be written as a list of commaseparated values (items) between square brackets. Important thing about a list is that the items in a list need not be of the same type. A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The main difference between the tuples and the lists is that the tuples cannot be changed unlike lists. Tuples use parentheses, whereas lists use square brackets.

Let’s say we have the following List and within that we have a Tuple as well −

mylist = [25, 50, 75, 100, 125, (20, 175, 100, 87), 500]

The output should be −

List = [25, 50, 75, 100, 125, (20, 175, 100, 87), 500]
List Length = 7

Count the elements in a list until an element is a Tuple using isinstance()

Use the isinstance() method to count the elements in a list until an element is a Tuple −

Example

def countFunc(k): c = 0 for i in k: if isinstance(i, tuple): break c = c + 1 return c # Driver Code mylist = [25, 50, 75, 100, 125, (20, 175, 100, 87), 500] print("List with Tuple = ",mylist) print("Count of elements in a list until an element is a Tuple = ",countFunc(mylist))

Output

List with Tuple = [25, 50, 75, 100, 125, (20, 175, 100, 87), 500]
Count of elements in a list until an element is a Tuple = 5

Count the elements in a list until an element is a Tuple using type()

Use the type() method to count the elements in a list until an element is a Tuple −

Example

def countFunc(k): c = 0 for i in k: if type(i) is tuple: break c = c + 1 return c # Driver Code mylist = [25, 50, 75, 100, 125, (20, 175, 100, 87), 500] print("List with Tuple = ",mylist) print("Count of elements in a list until an element is a Tuple = ",countFunc(mylist))

Output

List with Tuple = [25, 50, 75, 100, 125, (20, 175, 100, 87), 500]
Count of elements in a list until an element is a Tuple = 5

Updated on: 11-Aug-2022

385 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements