Start learning free

LESSON 221 OF 673 · LOOPS WITH STRINGS, LISTS & DICTIONARIES

Longest Word in Python: Tracking the Best So Far

Practice Read the full explanation

Given a list of strings words, return the longest word: the one with the most letters.

If several words share the longest length, return the first of them.

 

Example 1:

Input: words = ["I", "love", "pancakes"]
Output: "pancakes"
Explanation: "pancakes" has 8 letters, more than "I" (1) and "love" (4).

Example 2:

Input: words = ["apple", "kiwi", "mango"]
Output: "apple"
Explanation: "apple" and "mango" both have 5 letters, the most. "apple" comes first, so it is the answer.

Example 3:

Input: words = ["code"]
Output: "code"
Explanation: With only one word, it is the longest.

 

Constraints:

  • words has at least one word.
  • Every word is made of English letters, lowercase or uppercase.
  • On a tie, the answer is the first of the longest words.
STEP 1 OF 5
    Ctrl + Enter to check

    PYTHON · LOOPS WITH STRINGS, LISTS & DICTIONARIES

    Longest Word in Python, explained

    Problem overview

    The method longestWord receives a list of strings, words, and returns the word with the most letters. When several words share the greatest length, it returns the first of them. The list always has at least one word.

    For ["I", "love", "pancakes"] the answer is pancakes, which has 8 letters. For ["apple", "kiwi", "mango"], "apple" and "mango" both have 5, so the answer is apple, the one that comes first. With a single word, ["code"], that word is the answer.

    Approach: keep a champion

    Read the words one at a time and remember the longest one seen so far. Each new word either beats the champion, in which case it takes over, or it doesn't, and the champion stays. After the last word, the champion is the longest of all.

    The champion needs a starting value. Because the list is never empty, the first word is a safe choice: before any comparison, it is the best word we have.

    Step by step

    1. Store words[0] in longest. This works because there is always at least one word.
    2. Loop over words with for word in words. Each word gets one chance to beat the champion.
    3. Compare lengths with len(word) > len(longest). The comparison is strict. A word of equal length does not replace the champion, so on a tie the earlier word stays.
    4. Replace the champion inside the if with longest = word.
    5. Return longest after the loop, when every word has been compared.

    Tracing the tie example

    Take ["apple", "kiwi", "mango"]. The champion starts as "apple". The loop then asks, for each word, whether it is strictly longer than the champion:

    wordlonger than the champion "apple"?
    appleFalse
    kiwiFalse
    mangoFalse

    "mango" matches "apple" at 5 letters but doesn't exceed it, so the champion never changes and the function returns apple.

    The solution in Python

    class Solution:
        def longestWord(self, words: List[str]) -> str:
            longest = words[0]
            for word in words:
                if len(word) > len(longest):
                    longest = word
            return longest
    

    Notes on the code:

    • The first word is compared with itself. The loop starts at the first word, and len(words[0]) > len(longest) is false because they are the same string. It is harmless, and it keeps the loop simple.
    • Assigning a string only rebinds the name. Strings are immutable, and longest = word makes longest refer to the same string as word. Nothing is copied or changed.
    • The built-in alternative. max(words, key=len) does the same job, and it also returns the first longest word on a tie. Writing the loop once shows what max does for you.

    Edge cases and common mistakes

    • Using >=. With ["apple", "kiwi", "mango"] the loop would end with mango, because the last word of the longest length would win every tie. The task asks for the first.
    • Starting with an empty string. longest = "" also works for words that have letters. Starting from words[0] is the more general habit, since it also works for values such as numbers, where there is no obvious "empty" starting point.
    • Returning its length. The function returns the word itself, not len(longest).
    • Comparing the strings directly. word > longest compares alphabetical order, not length. "pancakes" and "zoo" show the difference: "zoo" is the greater string, but "pancakes" is the longer one.

    Testing

    • ["I", "love", "pancakes"] gives pancakes.
    • ["apple", "kiwi", "mango"] gives apple.
    • ["code"] gives code.
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free