Find min value in array > 0 Find min value in array > 0 python python

Find min value in array > 0


You can use a generator expression with min. This will set m as the minimum value in a that is greater than 0. It then uses list.index to find the index of the first time this value appears.

a = [4, 8, 0, 1, 5]m = min(i for i in a if i > 0)print("Position:", a.index(m))print("Value:", m)# Position: 3# Value: 1


You can use the min function and enumerate function, like this

result = min(enumerate(a), key=lambda x: x[1] if x[1] > 0 else float('inf'))print("Position : {}, Value : {}".format(*result)# Position : 3, Value : 1

This makes sure that, if the value is greater than 0, then use that value for the minimum value comparison otherwise use the maximum possible value (float('inf')).

Since we iterate along with the actual index of the items, we don't have to find the actual index with another loop.


Here is another way of doing it with a generator expression. Note how the values coming from enumerate (a and b) are swapped in the tuple to sort correctly.

value,position = min(((b,a) for a,b in enumerate(myArray) if b>0), default=(None,None))

The default argument will be returned when the generator expression returns nothing (i.e. there are no items greater than 0). The default can be set to whatever makes sense in the surrounding program logic - here returning None will allow you to test with either if value: or if position: