Count the elements till first tuple in Python

PythonServer Side ProgrammingProgramming

When it is required to count the elements up to the first tuple, a simple loop, the 'isinstance' method, and the 'enumerate' method can be used.

Below is a demonstration of the same −

Example

Live Demo

my_tuple_1 = (7, 8, 11, 0 ,(3, 4, 3), (2, 22))

print ("The tuple is : " )
print(my_tuple_1)

for count, elem in enumerate(my_tuple_1):
   if isinstance(elem, tuple):
      break
print("The number of elements up to the first tuple are : ")
print(count)

Output

The tuple is :
(7, 8, 11, 0, (3, 4, 3), (2, 22))
The number of elements up to the first tuple are :
4

Explanation

  • A nested tuple is defined and is displayed on the console.
  • The tuple is enumerated, and iterated over.
  • The isinstance method is used to check if the element in the tuple belongs to a certain type.
  • This result is stored in a counter since 'enumerate' was used.
  • It is displayed as output on the console.
raja
Published on 12-Mar-2021 10:04:48
Advertisements