The key in Python | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

The key in Python

txt = input() #your code goes here wrd = txt.split() a = max(wrd,key=len) print(a) So i have this code that i used for a task, But im confused on what is "key" actually is... Is it somekind of specific order that u put on the program to output word based on what it define, like mine for example i define the key on len "max(key=len)" ...will that mean that it will only output the word based on the highest len?

1st Sep 2021, 12:43 PM
Ervan
Ervan - avatar
2 Answers
+ 8
Ervan , max() function can search for the greatest number, but it also can search for the longest word. in this case the longest word will be reurned. the function that will be applied is len(), which is named in key=len. txt = input() or "this is groundcontrol to major tom" #your code goes here wrd = txt.split() a = max(wrd,key=len) print(a) # result is: groundcontrol
1st Sep 2021, 12:54 PM
Lothar
Lothar - avatar
+ 3
'key' is an optional parameter, which expects a function (or lambda) reference as argument. When specified, the function will be called for, and be given each element of the iterable (the first argument). In each call to the function, max() records the value returned by the len() function (element length in this case), and noted the largest one returned. For example: lst = "Coding is fun".split() # [ "Coding", "is", "fun" ] longest_word = max( lst, key = len ) Here max() calls len() passing "Coding", "is", "fun" in sequence, and noted for which element len() returns the largest value. In this case, "Coding" is the result, because it is the longest element. Some more examples here 👇 https://thepythonguru.com/JUMP_LINK__&&__python__&&__JUMP_LINK-builtin-functions/max/
1st Sep 2021, 1:20 PM
Ipang