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

Find five longest words in a List in Python and order them in alphabetical order

It’s the first time I am working with Python for a Uni assignment and I am facing a difficulty regarding a task that says: Extract five longest words in the entire text, create a List with those items and order them alphabetically. Print out these results on the screen (e.g., ‘Five longest words in this text ordered alphabetically are: “word1”, “word2”, “word3”, “word4”, “word5”’)

So, the code I created so far is:

print(longest_string)

second_longest_string = sorted(word_list, key=len)[-2]
print(second_longest_string)

third_longest_string = sorted(word_list, key=len)[-3]
print(third_longest_string)

fourth_longest_string = sorted(word_list, key=len)[-4]
print(fourth_longest_string)

fifth_longest_string = sorted(list_1, key=len)[-5]
print(fifth_longest_string) ```

I thought I could start by this and then proceed to the alphabetical order, but it looks like this code generates a different output every time, because inside the list there are many strings that have the same number of words. 

Any idea how I can proceed?

Thank you.

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

>Solution :

This will sort the word list based on length and then get 5 most lengthy words and then sort them based on alphabatical order

sorted_words = sorted(sorted(word_list, key=len)[-5:])

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