Start learning free

LESSON 374 OF 410 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: head v2 — First n Lines in Python

Practice

Extend your head command to take an integer n and return the first n lines of lines, joined by newline characters (\n). For this version you may assume 0 ≤ n ≤ len(lines). If n is 0 the result is the empty string.

Function signature:

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

Example:

Input: lines = ["alpha", "beta", "gamma", "delta", "epsilon"], n = 3

Output: "alpha\nbeta\ngamma"

When printed:
alpha
beta
gamma

Same idea as v1, but the cap is now n instead of the constant 10. Slice lines from index 0 up to n, then join with "\n".

lines[:n] gives you the first n elements. Pipe it through "\n".join(...).

The full solution:
class Solution:
    def head(self, lines, n):
        return "\n".join(lines[:n])

STEP 1 OF 1
    Ctrl + Enter to check

    Head V2 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