Start learning free

LESSON 604 OF 673 · PROJECTS: COMMAND-LINE TOOLS

cat v4 in Python: Joining Several Files with Nested Loops

Practice Read the full explanation

The real cat command can take many files as arguments and prints them one after another. Build that behavior. Given a list of "files" where each file is itself a list of lines, flatten all lines in order and join them with newlines.

A file can be empty (it adds no lines), and the list can hold no files at all; the result is then an empty string.

Function signature:

def concatCat(self, allLines: List[List[str]]) -> str:

Example:

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

Output: "hello\nworld\nfoo\nbar\nbaz"

When printed:
hello
world
foo
bar
baz

Two steps: first flatten the list of lists into a single flat list, preserving order. Then join that flat list with "\n".

Use a nested loop or a list comprehension:
flat = [line for fileLines in allLines for line in fileLines]
return "\n".join(flat)


The full solution:
class Solution:
    def concatCat(self, allLines):
        flat = []
        for fileLines in allLines:
            for line in fileLines:
                flat.append(line)
        return "\n".join(flat)

STEP 1 OF 5
    Ctrl + Enter to check

    PYTHON · PROJECTS: COMMAND-LINE TOOLS

    Cat V4 in Python, explained

    Problem overview

    The real cat command accepts many files and prints them one after another. This version models that with a new method, concatCat(self, allLines). The argument is a list of "files", and each file is itself a list of lines. The method puts all the lines of all the files into one sequence, in order, and joins them with newlines.

    A file can be empty, in which case it adds no lines, and the list can hold no files at all. Then the result is an empty string.

    For [["hello", "world"], ["foo", "bar", "baz"]] the result is 'hello\nworld\nfoo\nbar\nbaz'. Printed, it looks like this:

    hello
    world
    foo
    bar
    baz
    

    Approach: flatten, then join

    The input is a list of lists, but "\n".join needs a flat list of strings. Handing it the outer list directly would fail, because its items are lists, not strings. So the work has two stages. First flatten: walk over the files in order, and inside each file over its lines in order, collecting every line in one flat list. Second, join that flat list with "\n", the same final move as in the earlier versions.

    Order is preserved without any extra effort: files are visited first to last, and lines within a file first to last, so the flat list reads exactly as the real command would print it.

    Step by step

    1. Create an empty list named flat. It will hold every line of every file, with no lists inside it.
    2. Loop over the files with for fileLines in allLines. Each fileLines is one file, a list of lines.
    3. Loop over that file's lines with a second for, nested inside the first.
    4. Append each line to flat. An empty file never enters the inner loop, so it adds nothing.
    5. Return flat joined with "\n". This line has no extra indent, so it runs once, after every file has been read.

    The solution in Python

    class Solution:
        def concatCat(self, allLines):
            flat = []
            for fileLines in allLines:
                for line in fileLines:
                    flat.append(line)
            return "\n".join(flat)
    

    Details worth knowing about this solution:

    • Indentation shows the nesting. The append line is indented under the inner for, which is indented under the outer one. Put the return at the inner level and the method would return after the first line.
    • A list comprehension does the same flattening in one line: [line for fileLines in allLines for line in fileLines]. The for clauses read in the same order as the nested loops. The loop version above is the one the lesson builds.
    • Joining the outer list fails. "\n".join([["a"], ["b"]]) raises a TypeError, because each item is a list. Flattening has to come first.
    • Joining a single file's list would not be enough either: the lines of all files must end up in the same sequence before the join.

    Edge cases and common mistakes

    • No files. concatCat([]) returns '', since the outer loop does not run.
    • Empty files. concatCat([["a"], [], ["b"]]) returns 'a\nb'. The empty file contributes no lines, so no extra blank row appears. concatCat([[], []]) returns ''.
    • A blank line inside a file is still a line. concatCat([[""], [""]]) has two lines, both empty, and returns '\n': two empty rows around one separator.
    • No newline between files. The files are not separated by anything extra. The last line of one file and the first line of the next are separated by the same single \n as any two lines.
    • Mixing up the loop variables. The outer variable is a whole file, and the inner variable is a line. Appending fileLines would put a list inside flat, and join would raise a TypeError.
    • Returning inside the loops. The return must sit after both loops, at the method's indent.

    Testing

    • [["hello", "world"], ["foo", "bar", "baz"]] gives 'hello\nworld\nfoo\nbar\nbaz'.
    • [["a"], ["b", "c"]] gives 'a\nb\nc'.
    • [["a"], [], ["b"]] gives 'a\nb'.
    • [[""], [""]] gives '\n'.
    • [] and [[], []] both give ''.
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free