Python - Get the Index of first element greater than K

PythonServer Side ProgrammingProgramming

The values of items in a python list are not necessarily in any sorted order. More over there may be situation when we are interested only in certain values greater than a specific value. In this article we will see how we can get the

Using Enumeration

Using enumeration we get both the index and value of the elements in the list. Then we apply the greater than condition to get only the first element where the condition is satisfied. The next function goes through each list element one by one.

Example

 Live Demo

List = [21,10,24,40.5,11]
print("Given list: " + str(List))
#Using next() + enumerate()
result = next(k for k, value in enumerate(List)
if value > 25)print("Index is: ",result)

Running the above code gives us the following result

Output

Given list: [21, 10, 24, 40.5, 11]
Index is: 3

Using Filter and Lambda Functions

In the next example we take a lambda function to compare the given value with value at each index and then filter out those which satisfy the required condition. From the list of elements satisfying the required condition, we choose the first element at index 0 for our answer.

Example

 Live Demo

List = [21,10,24,40.5,11]
print("Given list: " + str(List))
#Using filter() + lambda
result = list(filter(lambda k: k > 25, List))[0]
print("Index is: ",List.index(result))

Running the above code gives us the following result

Output

Given list: [21, 10, 24, 40.5, 11]
Index is: 3

Using map and lambda

In the next example we take a similar approach but use map instead of filter. The map function is used to loop through each of the elements. Whenever the condition becomes true that index is captured.

Example

 Live Demo

List = [21,10,24,40.5,11]
print("Given list: " + str(List))
result = list(map(lambda k: k > 25, List)).index(True)
print("Index is: ",(result))

Running the above code gives us the following result

Output

Given list: [21, 10, 24, 40.5, 11]
Index is: 3
raja
Published on 23-Dec-2019 10:22:44
Advertisements