Find smallest element greater than K in Python

PythonServer Side ProgrammingProgramming

During data analysis using python we come across many scenarios where we have to filter out elements from a list meeting certain criteria. In this article we will see how to get an element from a list which is greater than the element but smallest among all such elements which are greater than the given element.

With min

We design a for loop to go through each element of the list while meeting the general criteria of it’s value greater than k. Then for all such elements we apply the min function to get the minimum value.

Example

 Live Demo

listA = [1,5,6, 7,11,14]

# Original list
print("Given list : ",listA)

k = 8

# using min
res = min(i for i in listA if i > k)

# Result
print("Missing elements from the list : \n" ,res)

Output

Running the above code gives us the following result −

Minimum element gerater than k :
11

With filter

Here we use the lambda function to get elements whose value is greater than K. Then apply the filter function to get only those values. Finally apply the min function to get the minimum value form this list.

Example

 Live Demo

listA = [1,5,6, 7,11,14]

# printing original list
print("Given list : ",listA)

k = 8

# using min
res = min(filter(lambda i: i > k, listA))

# Result
print("Minimum element gerater than k : \n" ,res)

Output

Running the above code gives us the following result −

Minimum element gerater than k :
11

With bisect_right

The bisect_right function is available in the bisect module. It bisects a list at a point greater than or equal to a certain parameter value supplied to it. In this example we take the list, sort it and then apply the bisect_right function. We get the index of the element which is greater than the required value.

Example

 Live Demo

from bisect import bisect_right
listA = [1,5,6, 7,11,14]

# printing original list
print("Given list : ",listA)

k = 8

listA.sort()
# Using bisect_right
res = listA[bisect_right(listA, k)]

# Result
print("Minimum element gerater than k : \n" ,res)

Output

Running the above code gives us the following result −

Minimum element gerater than k :
11
raja
Published on 26-Aug-2020 08:12:35
Advertisements