Start learning free

LESSON 11 OF 69 · PROJECTS: COMMAND-LINE TOOLS

Character Count in Python: sum() with a Generator Expression

Practice Read the full explanation

Build a tiny version of the character count of the Unix wc command. Given a list of lines, return the total number of characters across all lines as an integer.

Convention: count only the characters in each line — do not count the implicit newlines that separate them. Spaces and tabs inside a line count as one character each.

Note: this is a simplified version. The real wc -m also counts the newlines, and the real wc -c counts bytes, not characters. Here the answer is simply the sum of the line lengths. The input is plain ASCII text (other alphabets are counted differently by different languages).

Function signature:

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

Example:

Input: lines = ["hello", "world"]

Output: 10

"hello" has 5 chars and "world" has 5 chars, for a total of 10.

An empty line adds 0, and an empty list of lines gives 0.


Sum the length of every line. Python's sum combined with a generator expression makes this a one-liner.

The full solution:
class Solution:
    def countChars(self, lines):
        return sum(len(line) for line in lines)

STEP 1 OF 1
    Ctrl + Enter to check

    PYTHON · PROJECTS: COMMAND-LINE TOOLS

    Wc V3 in Python, explained

    Problem overview

    This is the third version of the wc tool. The method countChars receives a list of strings, lines, and returns the total number of characters in all of them. The convention is simple: add up the length of each line, and don't count the newlines that would separate the lines in a file. Spaces and tabs inside a line count as one character each.

    For ["hello", "world"] the answer is 10, because each word has 5 characters. An empty line adds 0 and an empty list gives 0. The lesson only uses plain ASCII text, where one character is one byte.

    Approach: sum the lengths

    The answer is the sum of len(line) over all lines. You could write a loop with a running total, as in the previous version, but this lesson introduces the shorter Python form: a generator expression passed to sum.

    len(line) for line in lines reads like the loop header, with the value to produce written first. It hands out one length at a time, and sum adds them as they arrive. Nothing needs to be stored in a list first.

    lines = ["a b", "", "\tx"]
    print([len(line) for line in lines])
    print(sum(len(line) for line in lines))
    
    [3, 0, 2]
    5
    

    The first line shows the individual lengths in a list; the second adds them. "a b" is 3 characters, the empty line is 0, and "\tx" is 2, because the tab counts as one character.

    Step by step

    1. Return the sum of the lengths. The whole method is one return. The generator expression produces len(line) for every line in lines, and sum adds them. When lines is empty, sum of nothing is 0, so no special case is needed.

    The solution in Python

    class Solution:
        def countChars(self, lines):
            return sum(len(line) for line in lines)
    

    When a generator expression is the only argument of a function call, it doesn't need its own parentheses: sum(len(line) for line in lines) is enough. It does the same as this loop:

    total = 0
    for line in lines:
        total += len(line)
    return total
    

    In Python 3, len of a string counts characters (code points), not bytes. For ASCII text the two agree. A string such as "é" is one character but takes two bytes when encoded as UTF-8, which is why the real wc -c and wc -m can disagree.

    Complexity

    Time is O(m) in the number of lines, since len of a string takes constant time in Python. Extra space is O(1), because the generator produces one number at a time.

    Edge cases and common mistakes

    • Counting newlines. The real wc -m adds one per line break. Here the total is only the sum of the line lengths, so ["hello", "world"] is 10, not 11 or 12.
    • Counting words instead. len(lines) is the number of lines, and len(line.split()) the number of words. Neither is the character count.
    • Using a list where a generator will do. sum([len(line) for line in lines]) gives the same number but builds a list first. The version without brackets is the idiomatic one.
    • Empty input. [] gives 0, and so does [""].

    Testing

    linesresult
    ["hello", "world"]10
    ["a b", "", "\tx"]5
    []0

    The next version builds on this one.

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