Start learning free

LESSON 372 OF 410 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: cat v4 — Concatenate Multiple Files in Python

Practice

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

    Cat V4 in Python

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