I have read this. I have also read documentation about max() method, but I don't understand what is the difference between these two
len(max(name_of_the_list))
len(max(name_of_the_list, key=len))
if we want to get the longest item in our list.
I have read this. I have also read documentation about max() method, but I don't understand what is the difference between these two
len(max(name_of_the_list))
len(max(name_of_the_list, key=len))
if we want to get the longest item in our list.
The first will compare the strings, and whichever is found alphabetically greatest, output its length (default behavior of max
).
The second will use the string's length as a key for the max
function, and find the string with maximum length, and output its length. Here, the len
refers to the python builtin len
function.
So both of these are not the same. Since you want to get the longest item in the list, use the second one as it is correct.
As a demo, consider the following
>>> name_of_the_list = ["abcdefgh", "ijkl"]
>>> max(name_of_the_list)
"ijkl"
>>> len(max(name_of_the_list))
4
>>> max(name_of_the_list, key=len)
"abcdefgh"
>>> len(max(name_of_the_list, key=len))
8
The function max
will use the function cmp
defined by the type to check which one is the greatest. With the parameter key
you can override this behavior specifying the function that need to be applied in order to compute the score of an item, in base of which max
will return the maximum.
max(name_of_the_list, key=len)
This will return the longest item in the list (the one whose len
returns the biggest number).
If name_of_the_list
contains strings, omitting the key
results in using the default cmp
function defined for the strings which is the alphabetical comparison.
The max
function will return the element which has the biggest key function, so if you wrap the call in another len(...)
you are getting the length of that element. In order to obtain that, it means that you don't need the information about the element anymore but only the maximum of the keys, so you could do:
max(len(x) for x in name_of_the_list)
of also the equivalent using map
:
max(map(len, name_of_the_list))
This way, you will tell python to compute the length of the elements and then return the max of these lengths.