Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the correct use of "key" in the min() function?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading