Assume we have been provided with a string.
s="This is my statement"
We have to get sentence as an output and this needs to be solved using list comprehension concept.
I have tried the code below and it gives me an empty list.
longest_word=[i for i in s.split() if len(i) == max(s)]
Looking for some valid solution/suggestions for this problem.
The error in your code is in the
max(s)expression. Themax()when used this way, returns the character with the highest ASCII value in the stringsand not the length of the longest word as you incorrectly assumed. So when you comparelen(i) == max(s), you're comparing the length of the current wordito a character fromswhich makes little sense, because a character (which is essentially a string of length 1) and the length of a word (which will be greater than 1 for any word other than a single character) will never be equal, the comparison will always evaluate toFalseand that's why you get empty list.To find the longest word(s) in the string
scan be constructed using themax()akeyargument where we do passlenfunction to be used to compare lengths, along with list comprehension to handle multiple words of the same maximum length:And when implemented, your test case would then produce: