Start learning free

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

Word Lengths in Python: Building a List with a Loop

Practice Read the full explanation

Given a list of strings words, return a list of integers with the length of every word, in the same order as the words.

The length of a word is the number of letters it has.

 

Example 1:

Input: words = ["I", "love", "pancakes"]
Output: [1, 4, 8]
Explanation: "I" has 1 letter, "love" has 4 and "pancakes" has 8.

Example 2:

Input: words = ["banana", "kiwi", "fig"]
Output: [6, 4, 3]
Explanation: The lengths keep the order of the words: first "banana", then "kiwi", then "fig".

Example 3:

Input: words = ["code"]
Output: [4]
Explanation: One word gives one length.

 

Constraints:

  • words has at least one word.
  • Every word is made of English letters, lowercase or uppercase.
  • The result has one length per word, in the same order as words.
STEP 1 OF 4
    Ctrl + Enter to check

    PYTHON · LOOPS WITH STRINGS, LISTS & DICTIONARIES

    Word Lengths in Python, explained

    Problem overview

    The method wordLengths receives a list of strings, words, and returns a list of integers: the length of each word, in the same order as the words.

    For ["I", "love", "pancakes"] the answer is [1, 4, 8]: "I" has 1 letter, "love" has 4 and "pancakes" has 8. A list with one word gives a list with one length, so ["code"] gives [4]. Uppercase letters count like any other: ["Hi", "HELLO"] gives [2, 5].

    Approach: transform every item

    Unlike a filter, nothing is skipped here. Every word produces exactly one number, so the result has the same length as the input. The pattern is: start with an empty list, visit each word, add one value per word, and return the list.

    Step by step

    1. Create an empty list named lengths. The numbers are added one at a time, so it starts with nothing in it.
    2. Loop over words with for word in words. The loop runs once per word.
    3. Append len(word) to lengths. Adding at the end keeps the lengths in the same order as the words.
    4. Return lengths after the loop. Returning inside the loop would end the function after the first word, and only one length would come back.

    Filtering and transforming

    Compare this with a loop that keeps only some items. A filter wraps the append in an if, and the result can be shorter than the input. Here there is no if, because every word counts, and what gets appended is not the word itself but a value computed from it. Many list problems are one of these two shapes, or a mix of both.

    The same loop would work for other measurements. Appending word.upper() instead of len(word) would build a list of uppercase words, with the same loop around it.

    The solution in Python

    class Solution:
        def wordLengths(self, words: List[str]) -> List[int]:
            lengths = []
            for word in words:
                lengths.append(len(word))
            return lengths
    

    Some details of the code:

    • len counts characters. For a string made of English letters, that is the number of letters.
    • The list grows as you append. Python lists have no fixed size, so there is no need to say in advance how many lengths will come.
    • The same job in one line. A list comprehension, [len(word) for word in words], builds the same list. The loop version is what this lesson practises, and it is the form to reach for when each item needs several statements.

    Edge cases and common mistakes

    • Returning too early. A return indented into the loop body stops after the first word.
    • Appending the word instead of its length. lengths.append(word) copies the words, so the result is a list of strings.
    • Mixing up len(words) and len(word). len(words) is the number of words in the list. For ["I", "love", "pancakes"] it is 3, while the lengths are 1, 4 and 8.
    • Sorting or deduplicating. Two words of the same length each give their own entry, and the order of the input is kept.

    Testing

    • ["I", "love", "pancakes"] gives [1, 4, 8].
    • ["code"] gives [4].
    • ["Hi", "HELLO"] gives [2, 5].
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free