Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - printing multiple shortest and longest words from a list


I need to go through a list and print the longest words in it. I can do this for just one word, but can't figure out how to print more than one, if there are two words that are three letters long, for instance. I've tried

list.sort (key=len, reverse =True)
print ("The longest word in the list is: " , list[0])

This works but only prints the first longest, which is no good for more than one longest word.

I've also tried :

p=0
for item in list:
    if len (item) > p:
        s=item
        p = len(item)
print (s)

This also the same as the previous code

I also need to do this for the shortest word in the list.

Apologies if this isn't a good question, it's my first.

like image 360
Jacobsayshi Avatar asked Nov 16 '25 21:11

Jacobsayshi


2 Answers

Firstly, don't ever use list as a variable name as it will override the built in type and could cause trouble later on.

You could do this for the longest words:

for i in lst:
    if len(i) == max(lst, key=len):
        print(i)

And for the shortest words:

for i in lst:
    if len(i) == min(lst, key=len):
        print(i)

The first code prints the strings which have the same length as the longest string. The second does the same, but with the shortest strings.

A small optimisation would be to precalculate the max/min length before the loop, so you don't need to recalculate it every time.

maxLen = max(lst, key=len)
for i in lst:
    if len(i) == maxLen:
        print(i)

The same can be done for the other loop.

like image 127
Volatility Avatar answered Nov 19 '25 11:11

Volatility


Your existing code could actually be modified to work without much trouble. Instead of keeping a single string in s, keep a list of strings. If you find one that's the same length as the previous longest, append it. If you find one that's even longer, throw out the list and start a new one. Like this:

p=0
s=[]
for item in lst:
    if len(item) > p:
        s=[item]
        p=len(item)
    elif len(item) == p:
        s.append(item)
print(s)
like image 45
abarnert Avatar answered Nov 19 '25 11:11

abarnert