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. The max()
when used this way, returns the character with the highest ASCII value in the string s
and not the length of the longest word as you incorrectly assumed. So when you compare len(i) == max(s)
, you're comparing the length of the current word i
to a character from s
which 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 to False
and that's why you get empty list.
To find the longest word(s) in the string s
can be constructed using the max()
a key
argument where we do pass len
function to be used to compare lengths, along with list comprehension to handle multiple words of the same maximum length:
longest_word_length = max(len(word) for word in s.split())
longest_word = [word for word in s.split() if len(word) == longest_word_length]
And when implemented, your test case would then produce:
$ python test.py
['statement']