Start learning free

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

Long Words Only in Python: Filtering a List with a Loop

Practice Read the full explanation

Given a list of strings words and an integer n, return the words that are longer than n characters.

A word must be strictly longer than n: a word with exactly n characters is left out. Keep the words in the order they have in words. If no word is long enough, the result is empty.

 

Example 1:

Input: words = ["apple", "kiwi", "banana", "fig"], n = 4
Output: ["apple", "banana"]
Explanation: apple has 5 characters and banana has 6. kiwi has exactly 4, so it is left out, and fig has only 3.

Example 2:

Input: words = ["hi", "to", "be"], n = 3
Output: []
Explanation: No word has more than 3 characters.

Example 3:

Input: words = ["go", "went", "gone", "went"], n = 3
Output: ["went", "gone", "went"]
Explanation: Every word longer than 3 characters is kept, a repeated one too, in its original order.

 

Constraints:

  • words has at least one word, and every word is made of lowercase English letters.
  • n is 0 or more.
STEP 1 OF 5
    Ctrl + Enter to check

    PYTHON · LOOPS WITH STRINGS, LISTS & DICTIONARIES

    Long Words Only in Python, explained

    Problem overview

    The method longWords receives a list of strings, words, and an integer n. It returns a new list holding only the words that have more than n characters, in their original order.

    With words = ["apple", "kiwi", "banana", "fig"] and n = 4 the result is ['apple', 'banana']. "apple" has 5 characters and "banana" has 6. "kiwi" has exactly 4, which is not more than 4, so it is left out, and "fig" is too short. When no word is long enough, as with ["hi", "to", "be"] and n = 3, the result is the empty list []. Repeated words stay repeated: ["go", "went", "gone", "went"] with n = 3 gives ['went', 'gone', 'went'].

    Approach: build a new list

    This is the basic filter pattern. Start with an empty list, look at each item once, and add the items that pass the test. The input list is never changed: the answer is a separate list.

    The loop meets the words from first to last, and append adds at the end of the result, so the order of the input is kept without any extra work.

    Step by step

    1. Create the empty list result. It collects the words that pass. If none does, it stays empty, which is exactly the answer the lesson wants in that case.
    2. Loop over words with for word in words. Each pass gives word one string from the list.
    3. Test the length. len(word) is the number of characters, and the condition is len(word) > n. The comparison is strict, so a word with exactly n characters fails it.
    4. Append the word inside the if, so only words that passed are added.
    5. Return result after the loop, once every word has had its turn.

    Tracing the first example

    With n = 4, the loop looks at one word at a time:

    wordlen(word)len(word) > 4
    apple5True
    kiwi4False
    banana6True
    fig3False

    Only "apple" and "banana" are appended, in that order, so the function returns ['apple', 'banana']. The same pattern, a condition around an append, filters by any other rule too.

    The solution in Python

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

    A few details are worth noting:

    • Indentation is the structure. The append line is indented under the if, which is indented under the for. The return lines up with the for, so it runs once, after the loop ends. Indented one level further, it would sit inside the loop and return after the first word.
    • len works on strings. It counts characters, the same way it counts the items of a list.
    • append changes the list in place and returns None, so there is nothing to assign back.

    Edge cases and common mistakes

    • Using >= instead of >. With ["apple", "kiwi", "banana", "fig"] and n = 4 that would keep "kiwi" too.
    • Returning inside the loop. The function would return after the first word, whether or not the rest are long enough.
    • n = 0. Every word has at least one letter, so every word is kept: longWords(["tree", "bee"], 0) returns ['tree', 'bee'].
    • Removing words from words while looping over it. Deleting items from a list during a for loop over it skips elements. Building a separate result list avoids the problem.

    Testing

    • words = ["apple", "kiwi", "banana", "fig"], n = 4 gives ['apple', 'banana'].
    • words = ["hi", "to", "be"], n = 3 gives [].
    • words = ["go", "went", "gone", "went"], n = 3 gives ['went', 'gone', 'went'].
    • words = ["tree", "bee"], n = 0 gives ['tree', 'bee'].
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free