Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python program that finds the longest word in a sentence using list comprehension

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading