Start learning free

LESSON 608 OF 673 · PROJECTS: COMMAND-LINE TOOLS

head v4 in Python: Negative n Drops the Tail

Practice Read the full explanation

Same signature as v2/v3, but now n may be negative. Real head -n -K prints all lines except the last K. So when n < 0 return all lines except the last |n|; when n ≥ 0 behave exactly like v3 (return the first n, capped at the input length). If |n| is at least the number of lines, nothing is left, so return the empty string.

Function signature:

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

Example (negative n):

Input: lines = ["a", "b", "c", "d", "e"], n = -2

Output: "a\nb\nc"

When printed:
a
b
c

Python's slice lines[:n] already does the right thing for both signs. When n is negative, the slice means "stop |n| from the end" — exactly what we want.

The full solution is the exact same one-liner from v2/v3:
class Solution:
    def head(self, lines, n):
        return "\n".join(lines[:n])

STEP 1 OF 1
    Ctrl + Enter to check

    PYTHON · PROJECTS: COMMAND-LINE TOOLS

    Head V4 in Python, explained

    Problem overview

    This version lets n be negative in head(self, lines, n). The real command head -n -K prints all lines except the last K. So when n is negative, the method returns every line except the last |n|. When n is 0 or more, it behaves as before: the first n lines, capped at the length of the input. If |n| is at least the number of lines, nothing is left and the result is an empty string.

    For ["a", "b", "c", "d", "e"] and n = -2, the last two lines are dropped and the result is 'a\nb\nc':

    a
    b
    c
    

    Approach: negative slice ends count from the back

    It looks like the method needs a branch: one case for n >= 0 and another for n < 0. It does not, because a slice treats a negative end position as an offset from the end of the list. In lines[:n], a negative n means "stop |n| items before the end". For five lines, lines[:-2] stops two items from the end and keeps the first three.

    Both signs follow from one rule: a negative bound -k is read as len(lines) - k, and a bound that falls outside the list is clipped to the list's edge. If |n| is at least the length, len(lines) - |n| is zero or below, which clips to the start, and the slice is empty.

    Step by step

    The lesson has one step: return the first n lines glued into one string, with a newline between each two. It is the same line as in versions 2 and 3. What this lesson adds is the understanding of why it works for a negative n: the slice stops that many items before the end, and the join glues what is left.

    The solution in Python

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

    Some details to keep in mind:

    • Negative positions count from the end in Python indexing and slicing. -1 is the last item, -2 the one before it. In a slice end, -k excludes the last k items.
    • Slices never raise IndexError. A bound that goes beyond either edge is clipped, which is why -10 on five lines gives an empty slice.
    • The same expression covers three cases. A positive n keeps that many lines, a too-big n keeps all, and a negative n drops the tail.
    • Zero is not negative. lines[:0] is empty, and -0 is just 0 in Python, so it never means "drop nothing". With n = 0 the result is ''.

    Edge cases and common mistakes

    • Dropping one line. head(["a", "b", "c", "d", "e"], -1) returns 'a\nb\nc\nd'.
    • |n| equal to the length. head(["a", "b", "c", "d", "e"], -5) returns '': every line is dropped.
    • |n| larger than the length. head(["a", "b", "c", "d", "e"], -10) also returns ''. It is not an error.
    • Positive n is unchanged. head(["a", "b", "c", "d", "e"], 8) returns all five lines, and n = 0 returns ''.
    • Computing the end by hand. lines[:len(lines) + n] looks equivalent, but for two lines and n = -3 it becomes lines[:-1] and returns ['a'], while the plain lines[:n] correctly gives an empty list.
    • Confusing this with lines[n:]. That slice drops the first lines and keeps the rest, which is the opposite job.

    Testing

    • ["a", "b", "c", "d", "e"] with n = -2 gives 'a\nb\nc'.
    • ["a", "b", "c", "d", "e"] with n = -1 gives 'a\nb\nc\nd'.
    • ["a", "b", "c", "d", "e"] with n = -5 gives ''.
    • ["a", "b", "c", "d", "e"] with n = -10 gives ''.
    • ["a", "b", "c", "d", "e"] with n = 0 gives ''.
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free