- Related Questions & Answers
- Find smallest element greater than K in Python
- Python Indices of numbers greater than K
- Python - Number of values greater than K in list
- Count of subarrays whose maximum element is greater than k in C++
- Get first element of each sublist in Python
- Count of alphabets having ASCII value less than and greater than k in C++
- Get first index values in tuple of strings in Python
- Count the number of words having sum of ASCII values less than and greater than k in C++
- What happens if try to access an element with an index greater than the size of the array in Java?
- Adding elements of an array until every element becomes greater than or equal to k in C++.
- Finding the index of first element in the array in C#
- Program to split lists into strictly increasing sublists of size greater than k in Python
- Get the first element of array in JavaScript
- Count subarrays with all elements greater than K in C++
- Get the index of the first occurrence of a separator in Java

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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 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.

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

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

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.

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

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

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.

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

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

Advertisements