Python - Find the shortest word in a list

rabbit picture rabbit · Mar 29, 2015 · Viewed 12.2k times · Source

Hi all I know there may have been a few similar questions asked already but I would appreciate it if you could give me a more specific solution for what I have attempted.

Basically the program should return the shortest word in the list. The shortest word cannot be an empty string. <-- I'm also not sure how to do this part.

Thanks for the help! : )

Main Program:

    n = int((input("Enter amount of words: "))
    sw = st.word(n)
    print("The shortest word is: {0:.s}" .format(sw))

Function:

    def word(n):

        l1 = []

        for i in range(n):
            words = str(input("Enter word: "))
            l1.append(words)

        s = l1
        nxt = l1

        for i in range(n+1): 
            if s[i] < nxt[i+1]:
                smallest = s[i]
            if nxt[i+1] < s[i]:
                smallest = nxt[i+1]
        return smallest

Answer

Marcin picture Marcin · Mar 29, 2015

You could just use build in min function:

l = ["ab", "abc", "", "fff", "gdfgfdg","a", "3455"]


print(min((word for word in l if word), key=len))
# results in: a

Some explanation:

  • (word for word in l if word) is generator expression,

  • if word condition assures that empty strings are not used,

  • key=len uses length of each word to look for a minium