Python | Get the index of the first element greater than K

Python Methods and Functions

Method # 1: Using next () + enumerate ()
Using next () returns an iterator to the element that used enumerate () . We simply put a condition for the enumeration and next () selects the appropriate index of the element.

# Python3 demo code
# just find the index of the first element
# more K
# using enumerate () + next ()

  
# initializing list

test_list = [ 0.4 , 0.5 , 11.2 , 8.4 , 10.4 ]

  
# print original list

print ( "The original list is:" + str (test_list))

 
# using enumerate () + next () to find the index
# the first element is slightly larger than 0.6

res = next ( x for x, val in enumerate (test_list)

if val & gt;  0.6 )

 
# print result

print ( "The index of element just greater than 0.6:"

+ str (res))

Exit:

 The original list is: [0.4, 0.5, 11.2, 8.4, 10.4] The index of element just greater than 0.6: 2 

Method # 2: Using filter () + lambda
Using a filter with a lambda expression can also to help us achieve this particular task, index index 0 is used to indicate that the first element greater than the value should be taken.

# Python3 demo code
# find the index of the first element just
# more K
# using a filter () + lambda

 
# initializing list

test_list = [ 0.4 , 0.5 , 11.2 , 8.4 , 10.4 ]

 
# print original list

print (  "The original list is:" + str (test_list))

 
# using the () + lambda filter
# it is easy to find the index of the first element
# greater than 0.6

res = list ( filter ( lambda i: i & gt;  0.6 , test_list)) [ 0 ]

 
# print result

print ( "The index of element just greater than 0.6: "

  + str (test_list.index (res)))

Output:

 The original list is: [0.4, 0.5, 11.2, 8.4, 10.4] The index of element just greater than 0.6: 2 

Method # 3: Using map () + index ()
map () along with index () can also return the desired element index and has the same inner workings as method 1 as discussed above.

# Python3 demo code
# just find the index of the first element
# more K
# using map () + index ()

  
# initializing list

test_list = [ 0.4 , 0.5 , 11.2 , 8.4 , 10.4 ]

  
# print original list

print ( "The original list is:" + str (test_list))

 
# using map () + index ()
# just find the index of the first element
# greater than 0.6

res = list ( map ( lambda i: i & gt;  0.6 , test_list)). index ( True )

 
# print result

print ( "The index of element just greater than 0.6: "

  + str (res))

Exit :

 The original list is: [0.4, 0.5, 11.2, 8.4, 10.4] The index of element just greater than 0.6: 2 




Get Solution for free from DataCamp guru