Why does the min function in Python work incorrectly?

You need to get the minimum value from tuple with the exception of zeros. I wrote this function:

print(min(values, key=lambda x: x or max(values)))

If values=(1, 0, 1, 0), prints 1, all correct, but if values = (0, 1, 0, 1, 1, 0), prints 0. Tell me, please, what could be the problem?

Author: MaxU, 2020-11-22

2 answers

This is because zero has weight it turns out the same as the unit:

values = (0, 1)

print(0 or max(values))  # 1
print(1 or max(values))  # 1

And the function returns the first one the minimum value found. Therefore, if 0 goes before 1, then it returns:

The key argument specifies a one-argument ordering function like that used for list.sort().

If multiple items are minimal, the function returns the first one encountered.


I would like to Your location has filtered out the values, for example like this:

values = (0, 1)
result = min(x for x in values if x != 0)  # 1
 3
Author: nomnoms12, 2020-11-22 11:17:04

Why is it so difficult?

res = min(filter(lambda x: x != 0, values))
 1
Author: Zhihar, 2020-11-22 11:17:59