Python | Count the elements up to the first tuple

Counters | Python Methods and Functions

Method # 1: Using the loop + isintance () + enumerate ()
This problem can be solved using the above functions. In this we just iterate over the elements using enumerate () to get its index and check the type using isinstance () .

# Python3 code to demonstrate how it works
# Elements before the first tuple
# using isinstance () + enumerate () + loop

 
# initialize tuple

test_tup = ( 1 , 5 , 7 , ( 4 , 6 ), 10 )

 
# print the original tuple

print ( "The original tuple:" + str (test_tup))

 
# Elements before the first tuple
# using isinstance () + enumerate () + loop

for count, ele in enumerate (test_tup):

if isinstance (ele, tuple ):

  break

 
# print result

print ( "Elements till the first tuple:" + str (count))

Output:

 The original tuple: (1, 5, 7, (4, 6), 10) Elements till the first tuple: 3 

Method # 2: Using takewhile () + sum () + isinstance () + lambda
A combination of the above functions can also be used to solve this problem. In this we use takewhile () to iterate to the tuple and sum () to check the counter.

# Python3 code to demonstrate how it works
# Elements before the first tuple
# using takewhile () + sum () + isinstance () + lambda

from itertools import takewhile

 
# initialize the tuple

test_tup = ( 1 , 5 , 7 , ( 4 , 6 ), 10 )

 
# print the original tuple

print ( "The original tuple:" + str ( test_tup))

 
# Elements before the first tuple
# using takewhile () + sum () + isinstance () + lambda

res = sum ( 1 for sub in takewhile ( < code class = "keyword"> lambda ele: not isinstance (ele, tuple ), test_tup))

 
# print result

print ( "Elements till the first tuple:" + str (res))

Output:

 The original tuple: (1, 5, 7, (4, 6), 10) Elements till the first tuple: 3 




Get Solution for free from DataCamp guru