0

I would like to improve my understanding regarding the key argument of the builtin max function. Please consider the following example:

I have a list of lists, and I want to find the one with the biggest length. I can write the straight forward solution:

maximum = 0
for l in lists:
   maximum = max(maximum, len(l))

However I would prefer to avoid an explicit for loop using the key argument of max. As I understand it, the key will apply its argument to each element in the input and then compare those outputs. So this should work:

maximum = max(lists, key=len)

I believe it should work because according to my (apparently false) understanding the above statement would be equivalent to applying length to each element and then invoking max:

max([len(l) for l in text_tokenized])

What am I missing?

pilu
  • 720
  • 5
  • 16
  • have you looked at https://stackoverflow.com/questions/30902558/finding-the-longest-list-in-a-list-of-lists-in-python ? – Kyhle Ohlinger Sep 10 '18 at 12:19
  • It returns the list itself not the length. If you want to get the length use: `maximum = len(max(lists, key=len))` – ikkuh Sep 10 '18 at 12:21
  • 1
    Are you looking for `max(map(len, lists))` – Grijesh Chauhan Sep 10 '18 at 12:21
  • What's the problem with your solution? It seems fine to me. Are you just asking if your thinking is correct? In which case: yes, it is. But you should really ask a tangible question with, if appropriate, a [mcve]. – jpp Sep 10 '18 at 12:26
  • I am indeed trying to find out what I am missing from how max works, not how to solve the example – pilu Sep 10 '18 at 12:38

1 Answers1

2

I believe it should work because according to my (apparently false) understanding the above statement would be equivalent to applying length to each element and then invoking max:

No, The code

maximum = max(lists, key=len)

Means, find an "element" from lists which having maximum value of len(element)

Whereas, what you intended to find value of len(element). one line quvilent of your code:

maximum = 0
for l in lists:
   maximum = max(maximum, len(l))

would be

max(map(len, lists))

or may be using len(max(lists, key=len))

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208