How to get the longest word from a list or string. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How to get the longest word from a list or string.

#I tried up to getting length of each word.. txt=input() print("your input is--"+txt) def words(txt): return (txt.split()) #print(words(txt)) wordss=words(txt) print(wordss) def lenth(): for line in wordss: if "\n" in line: print(line+" -- " +str(len(line)-1)) else: print(line+" -- " +str(len(line))) lenth() #print(max(str(line))) """ It prints ==> your input is--how to get the longest word from the list or a sentence ['how', 'to', 'get', 'the', 'longest', 'word', 'from', 'the', 'list', 'or', 'a', 'sentence'] how -- 3 to -- 2 get -- 3 the -- 3 longest -- 7 word -- 4 from -- 4 the -- 3 list -- 4 or -- 2 a -- 1 sentence -- 8 """

3rd Feb 2021, 12:03 AM
MALLIKHARJUNA
MALLIKHARJUNA - avatar
5 Answers
+ 8
If you want to print them in order from longest to shortest, you could do this. words = sorted(input().split(), key=len, reverse=True) for word in words: print(word, "len =", len(word))
3rd Feb 2021, 3:17 AM
David Ashton
David Ashton - avatar
+ 3
If you just want to get the longest word (without representations) Just print that string. If this is a challenge (maybe not), you dont need representations, you can just print the string right away. https://code.sololearn.com/cQ95W1GB02Dg/?ref=app
3rd Feb 2021, 1:13 AM
noteve
noteve - avatar
+ 2
max here is not a function, it is a variable that holds the string that has greatest value temporarily. It is iterating each string, if a string length is greater than the previous ones then that will be the new "max" value. This is what it looks like using max function: print(max(input().split(), key=len))
3rd Feb 2021, 1:31 AM
noteve
noteve - avatar
+ 1
Dude how we do it with out max function
3rd Feb 2021, 1:29 AM
MALLIKHARJUNA
MALLIKHARJUNA - avatar
+ 1
Ok i didn't even look my bad Tnx
3rd Feb 2021, 1:34 AM
MALLIKHARJUNA
MALLIKHARJUNA - avatar