Start learning free

LESSON 610 OF 673 · PROJECTS: COMMAND-LINE TOOLS

Word Count in Python: Counting Words with split()

Practice Read the full explanation

Build a tiny version of the Unix wc -w command. Given a list of lines, return the total number of words (whitespace-separated tokens) across all lines as an integer.

Function signature:

def countWords(self, lines: List[str]) -> int:

Example:

Input: lines = ["hello world", "foo bar baz", ""]

Output: 5

The empty string contributes 0 words, "hello world" contributes 2, and "foo bar baz" contributes 3. Total: 5.

Words are separated by one or more spaces or tabs, and leading or trailing whitespace is ignored. A line with no words (empty, or only whitespace) contributes 0, and an empty list of lines gives 0. The input is plain ASCII text.


Iterate over the lines and accumulate the word count. The trick is splitting on whitespace correctly so that empty / whitespace-only lines contribute zero.

Calling str.split() with no arguments handles whitespace beautifully — multiple spaces are treated as one, and an empty string produces an empty list.
total += len(line.split())


The full solution:
class Solution:
    def countWords(self, lines):
        total = 0
        for line in lines:
            total += len(line.split())
        return total

STEP 1 OF 4
    Ctrl + Enter to check

    PYTHON · PROJECTS: COMMAND-LINE TOOLS

    Wc V2 in Python, explained

    Problem overview

    This is the second version of the wc command-line tool. The method countWords receives a list of strings, lines, and returns the total number of words in all of them as an integer. A word is a run of characters separated from the next one by spaces or tabs.

    For ["hello world", "foo bar baz", ""] the answer is 5: the first line has 2 words, the second has 3, and the empty string has none. Extra spaces at the start, at the end or between words don't create words, a line holding only whitespace counts 0, and an empty list gives 0.

    Approach: split each line, count the pieces

    Counting spaces doesn't work, because "a b" has two spaces and two words, while " a " has four spaces and one word. It is simpler to cut every line into its words and count the pieces. Python's str.split() does exactly that when you call it with no argument.

    With no argument, split() treats any run of whitespace as one separator and ignores whitespace at both ends, so it never returns empty pieces:

    print("  a \t b ".split())
    print("".split())
    print("a  b".split(" "))
    
    ['a', 'b']
    []
    ['a', '', 'b']
    

    The third line shows the trap. split(" "), with a space as the argument, cuts at every single space, so two spaces in a row produce an empty string between them, and that empty string would be counted as a word. Use the bare split().

    The total is the sum of the piece counts of all lines. A line without words contributes 0, which is what len([]) gives.

    Step by step

    1. Create total and set it to 0. A running total starts at zero, before any line has been looked at.
    2. Loop over lines with for line in lines, so every line gets the same treatment.
    3. Add the line's word count. line.split() gives the list of words and len measures it. Empty and whitespace-only lines add 0 without any special case.
    4. Return total after the loop. The return is not indented under the for, otherwise the function would stop after the first line.

    The solution in Python

    class Solution:
        def countWords(self, lines):
            total = 0
            for line in lines:
                total += len(line.split())
            return total
    

    total += len(line.split()) is shorthand for total = total + len(line.split()). The method belongs to a class, so it takes self first; the code never uses it. The lesson's type hints (List[str], -> int) are optional in Python and don't change what runs.

    Because split() splits on all whitespace, a tab between words separates them just like a space does: "a\tb" has two words.

    Complexity

    Time is O(n) in the total number of characters, because split() reads each line once and the loop touches every line once. The extra space is O(w) for the largest list of words that split() builds for a single line, which is thrown away before the next line.

    Edge cases and common mistakes

    • Splitting on a single space. "a b".split(" ") has three pieces, so the count is 3 instead of 2. A line made only of spaces, such as " ", would give several empty pieces instead of 0.
    • Counting spaces and adding 1. This fails for the empty line (it would give 1) and for any line with leading, trailing or repeated spaces.
    • Returning inside the loop. Indent the return one level too far and only the first line is counted.
    • An empty list. The loop doesn't run, so total stays 0, which is the right answer.

    Testing

    Inputs worth trying, with the results the solution returns:

    linesresult
    ["hello world", "foo bar baz", ""]5
    [" a \t b ", " "]2
    []0
    ["a\tb"]2

    The next version builds on this one.

    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free