-1

I am a bit puzzled by the behavior of the key argument in min() and max()

Let's say I have the following list: c=[10,11,15,25,50]

I want the max value above 20, so I do: max(c,key= lambda x: x>20). Result is 25, should be 50.

I want the max value below 20, so I do: max(c,key= lambda x: x<20). Result is 10, should be 15.

Same thing with min(). If I want the min values above 20 (min(c,key= lambda x: x>20)), this will give me 10, instead of 25.

Can someone please help explain? I would like to understand better in order to avoid mistakes when dealing with different conditions.

Emanuele G
  • 33
  • 5
  • 1
    A key of `lambda x: x>20` is just going to return `True` if `x>20`, `False` otherwise. It's not going to return the value of `x` itself. – Random Davis Mar 30 '21 at 15:23
  • What makes you think ``key= lambda x: x>20`` would *restrict* the output to values larger than 20? What "restriction" do you assume is applied by ``max(c,key= lambda x: -x)``? – MisterMiyagi Mar 30 '21 at 15:27

1 Answers1

2

That is not the correct way to use max instead you'd want to use a generator expression to filter out elements, then take the max of that

>>> max(i for i in c if i > 20)
50

If you pass that condition to key then the return value of that lambda will be used for sorting, and all of the values will simply be True or False (where False < True) so you'll get the first of the falsey values, in this case 10.

The key argument is really intended to be used if you want to specify a way to access a particular piece of data for each item in your list. For example say I have this class

class point:
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

If I want to find the largest point based on its .y value, that is a good time to use the key argument

>>> data = [point(1,2,3), point(3,2,1), point(9,8,7)]
>>> p = max(data, key = lambda pt: pt.y)
>>> p.y
8
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • Thanks for your comment @Cory. I was actually using a piece of code for dates I found here: https://stackoverflow.com/questions/60109868/find-closest-past-date-in-list-of-dates It was unclear to me how that worked so was playing with simple example. – Emanuele G Mar 30 '21 at 15:35