Python Forum

Full Version: How to get index of minimum element between 3 & 8 in list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have the below list, and I want to get the index of minimum element which is >3 & <=8.

my_list = [-1,4,-5,0,2,11,9,8,6]
#below only grep minimum whose value >0 
m = min(i for i in my_list if i > 0)

but I want a minimum element between 3 & 8
I use the below code, but it does not work. It still gives me an answer is 2.
m2 = min(i for i in my_list if i > 0 & i<=8)
Someone help, how to achieve this.
If your condition is i > 0 then 2 is the correct answer.

In order to avoid such typos it is more readable to write:

>>> my_list = [-1,4,-5,0,2,11,9,8,6]
>>> min(item for item in my_list if 3 < item <= 8)
A different form:

def condition(x):
    return 3 < x <= 8

my_list = [-1,4,-5,0,2,11,9,8,6]
minimum = min(filter(condition, my_list))
print("Minimum is", minimum)
I use it very rare. There are so many possibilities to solve this.