Start learning free

LESSON 373 OF 410 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: head v1 — First 10 Lines in Python

Practice

Build a tiny version of the Unix head command. Given a list of lines, return the first 10 lines joined by newline characters (\n). If the input has fewer than 10 lines, return all of them. If there are no lines at all, return the empty string.

Function signature:

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

Example:

Input: lines = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"]

Output: "a\nb\nc\nd\ne\nf\ng\nh\ni\nj"

When printed:
a
b
c
d
e
f
g
h
i
j

Get the first 10 elements out of lines, then join them with "\n". Python slicing is the easiest way to grab the first 10 — and slicing is safe even when the list is shorter.

Use the slice lines[:10] — this returns up to 10 elements. Then call "\n".join(...) on the slice.

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

STEP 1 OF 1
    Ctrl + Enter to check

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