-7

What does this key=func part mean in max(a,b,c,key=func) here https://docs.python.org/2/library/functions.html#min?

I know how does this function work in Python. But usually I see it used just simply as z = max(a, b, c) But in Python docs I've found this part and I don't understand it. Is it some additional optional feature of this function or what?

  • 8
    That **exact paragraph you link to** tells you what the `key` argument does. – Daniel Roseman Jan 19 '17 at 15:27
  • 1
    @DanielRoseman Well, it's one sentence saying "The optional key argument specifies a one-argument ordering function like that used for list.sort().". By itself that might not be terribly helpful, but it points you in the right direction (to look at the documentation for `list.sort()` which provides a more detailed explanation of its `key` parameter). – Tagc Jan 19 '17 at 15:31
  • I agree with Tagc: a lot of users don't see the point until they see an exact example. – Jean-François Fabre Jan 19 '17 at 15:35

1 Answers1

6

it allows to define a criterion which replaces the < comparison between elements.

For instance:

>>>l = ["hhfhfhh","xx","123455676883"]
>>>max(l, key=len)
'123455676883'

returns the longest string in the list which is "123455676883"

Without it, it would return "xx" because it's the highest ranking string according to string comparison.

>>>l = ["hhfhfhh","xx","123455676883"]
>>>max(l)
'xx'
Mohammad Yusuf
  • 16,554
  • 10
  • 50
  • 78
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
  • Thanks a lot. ) That's more understandable for me. So, basically in the place of `func` can be used any function, which can be applied to elements of the list with dot notation (meaning that it's included in the String class or whatever class). Is that correct? – Constantine Ketskalo Jan 23 '17 at 15:58
  • yes. That's correct. And if it needs some tweaking, you can use `lambda` to define your own functions. Ex: provide len-3 would be: `lambda s : len(s)-3` – Jean-François Fabre Jan 23 '17 at 16:31