Hi guys. Can any one explain what the (key = len) meaning? | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite
+ 1

Hi guys. Can any one explain what the (key = len) meaning?

https://code.sololearn.com/cBj0dBhx3u4f/?ref=app

26th Apr 2022, 11:09 AM
Abdullah Essa
6 Réponses
+ 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'
26th Apr 2022, 11:16 AM
Per Bratthammar
Per Bratthammar - avatar
+ 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.
26th Apr 2022, 11:37 AM
Stefanoo
Stefanoo - avatar
+ 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
26th Apr 2022, 3:53 PM
Lothar
Lothar - avatar
+ 1
Thanks for your help my friend Per Bratthammar
26th Apr 2022, 11:31 AM
Abdullah Essa
+ 1
I am gratitful to you Stefanoo
26th Apr 2022, 11:48 AM
Abdullah Essa
+ 1
Thanks for your great addition Lothar
27th Apr 2022, 9:49 AM
Abdullah Essa