Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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. A Python list can contain items of different types, including tuples. The goal is to iterate through the list and count how many elements appear before the first tuple is encountered.
For example, given the following list −
mylist = [25, 50, 75, 100, 125, (20, 175, 100, 87), 500]
There are 5 elements (25, 50, 75, 100, 125) before the first tuple (20, 175, 100, 87), so the count is 5.
Using isinstance()
The isinstance() function checks whether an object is an instance of a given type. We loop through the list, incrementing a counter, and break as soon as a tuple is found ?
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 before Tuple =", countFunc(mylist))
The output of the above code is ?
List with Tuple = [25, 50, 75, 100, 125, (20, 175, 100, 87), 500] Count of elements before Tuple = 5
Using type()
The type() function returns the exact type of an object. We can compare it against tuple using the is keyword. Unlike isinstance(), this does not consider subclasses − it checks for an exact type match ?
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 before Tuple =", countFunc(mylist))
The output of the above code is ?
List with Tuple = [25, 50, 75, 100, 125, (20, 175, 100, 87), 500] Count of elements before Tuple = 5
Conclusion
Both isinstance() and type() can be used to count list elements until a tuple is found. Prefer isinstance() when you want to handle subclasses of tuple as well, and type() when you need a strict exact-type check.
