Longest Word | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

Longest Word

Given a text as input, find and output the longest word. Sample Input this is an awesome text Sample Output awesome txt = input() print(max(txt.split(),key=len)) Can someone explain the part of "key=len" please? I am new to python and sorry for my bad English.

6th Feb 2022, 8:26 AM
Kusa Tero
4 Answers
+ 7
Hello Kusa Tero The key tells the max function exactly what the maximum should be: In your case the length of the word. Without key it would work alphabetically. e.g. this > awesome so max would return this.
6th Feb 2022, 8:39 AM
Denise Roßberg
Denise Roßberg - avatar
+ 3
A bit more involved explanation. The iterables in Python can contain any type of data. Not just numbers, but also strings, booleans, even other containers, and instances of custom objects. Functions such as sort, max and min, work under the assumption, that there is a meaningful way to compare all elements of the iterable with each other. In case of numbers it is trivial to say which one is bigger. In case of strings, the default ordering is alphabetical, so for example 'a' < 'ba' But by providing a function as key argument, we can express a different ordering logic. This can be a lambda (anonymous function), or a reference to a function which takes a single argument. Each value in the iterable is transformed using this function, and the order is based on this result. Expressing with lambda: max(words, key=lambda w: len(w)) This can be simplified as: max(words, key=len)
6th Feb 2022, 11:12 AM
Tibor Santa
Tibor Santa - avatar
+ 1
Thanks guys
6th Feb 2022, 11:24 AM
Kusa Tero
+ 1
txt = input() #To find the longest word you can append the words inside a list , Then use len() to find the longest one. list=txt.split(" ") list2=[] for i in list: list2.append(len(i)) for x in list: if len(x)==max(list2): print(x)
8th Feb 2022, 6:24 AM
Erfan Bazri
Erfan Bazri - avatar