+ 1
Hi guys. Can any one explain what the (key = len) meaning?
6 Answers
+ 3
# Hi! It uses max according to the words length:
>>> wds = ("a", "b", "aaaaa", "aaa", "aa")
>>>
>>> print(f"{max(wds) = }")
max(wds) = 'b'
>>>
>>> print(f"{max(wds, key=len) = }")
max(wds, key=len) = 'aaaaa'
+ 3
len is a built in function.
You can write
print(len(txt))
and you will get the length of your string.
with
txt.split(' ')
You get a list with strings.
And the max function wants as parameter a list and a function which returns a number.
Then it uses the given function of each list item.
And returns the item with the largest result.
+ 3
Abdullah Essa ,
just an other information about the functions that can be used with the "key=" argument.
beside using built-in functions, you can also use your own defined funtions by using "def" or by using lambda functions.
this is how an expression is composed: outer_function(iterable, key=inner_funtion)
the return value of the inner function will be taken to perform the calculation and output of the outer function
+ 1
Thanks for your help my friend Per Bratthammar
+ 1
I am gratitful to you Stefanoo
+ 1
Thanks for your great addition Lothar