Start learning free

LESSON 375 OF 410 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: head v3 — Cap n at len(lines) in Python

Practice

Same signature as v2, but now n may be larger than the number of lines. If n > len(lines) simply return all the lines (don't crash, don't pad). For this version assume n ≥ 0. If n is 0, or there are no lines, the result is the empty string.

Function signature:

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

Example:

Input: lines = ["alpha", "beta", "gamma"], n = 10

Output: "alpha\nbeta\ngamma"

When printed:
alpha
beta
gamma

Python slicing already handles the over-cap case for you. lines[:n] with n larger than len(lines) simply returns the whole list — no extra logic needed.

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

STEP 1 OF 1
    Ctrl + Enter to check

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