I have a question about the min() function in Python. I am confused about the use of the "key" option in min(). Could someone explain how key works in min(), especially in relation to a lambda function?
For example:
lst = [10, -5, 20, 1]
min(lst, key=lambda x: x > 0)
As far as I understand, this expression should find the minimum element in the list lst that is greater than zero. However, it returns -5 instead of 1, which is the minimum element of lst that is greater than zero. Can someone explain why this happens and how I should correctly use key in the min() function?
Your key function key=lambda x: x > 0
just evaluates to a Boolean. You can see this you you write it out in a loop:
lst = [10, -5, 20, 1]
for item in lst:
print(item > 0)
Booleans are subclasses of integers, so the conversion is easy:
lst = [10, -5, 20, 1]
for item in lst:
print(int(item > 0))
Guess what; -5
is the only value that returns False
(0
) so that's the result you get as the minimum (that was your key).
You could filter
this list but, really, you'd just be better re-building it with positive elements and then using min()
without a key
, to be clear on what you're doing:
lst = [10, -5, 20, 1]
lst = [item for item in lst if item > 0]
print(min(lst))