Start learning free

LESSON 607 OF 673 · PROJECTS: COMMAND-LINE TOOLS

head v3 in Python: When n Is Too Big

Practice Read the full explanation

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

    PYTHON · PROJECTS: COMMAND-LINE TOOLS

    Head V3 in Python, explained

    Problem overview

    The head method keeps the signature from version 2: head(self, lines, n). What changes is the promise about n. It may now be larger than the number of lines. In that case the method returns all the lines, without crashing and without padding. For this version n is never negative. When n is 0, or when there are no lines, the result is an empty string.

    For ["alpha", "beta", "gamma"] and n = 10, the result is 'alpha\nbeta\ngamma':

    alpha
    beta
    gamma
    

    Approach: let the slice stop at the end

    A first instinct is to guard against a too-large n: compare it with len(lines) and use the smaller of the two, or loop and stop at the end of the list. That works, but the code from the previous version needs no change. A slice quietly stops at the end of the list: when the end position lies past the last item, Python simply takes everything up to the last item. lines[:n] with a huge n is a copy of the whole list.

    So this lesson is less about writing new code and more about understanding why the same line is already correct. It is worth knowing that slices behave this way, because indexing does not: lines[10] on a three-item list raises IndexError, while lines[:10] never does.

    Step by step

    The lesson has one step: return the first n lines joined into one string, with a newline between each two. It is the same line as in version 2. Reading it again with the new case in mind: lines[:n] gives at most n items, and fewer when the list is shorter, and "\n".join(...) glues whatever it gets. With 5 lines and n = 8, the slice holds all 5 and the join returns them with four newlines between them.

    The solution in Python

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

    Details behind it:

    • Out-of-range slice bounds are clipped. A slice never raises IndexError. Bounds beyond the list are cut back to its start or end. Only a single index like lines[i] is checked strictly.
    • "At most" is what a slice means. The result has min(n, len(lines)) items when n is not negative.
    • No padding. The slice does not add empty lines to reach n. Five lines with n = 8 give five lines, not eight.
    • The list is not modified. The slice is a new list.

    Edge cases and common mistakes

    • n larger than the list. head(["a", "b", "c", "d", "e"], 8) returns 'a\nb\nc\nd\ne', and head(["alpha", "beta", "gamma"], 10) returns 'alpha\nbeta\ngamma'.
    • An empty list with any n. head([], 5) returns '': the slice of an empty list is empty.
    • n = 0. The result is '', as in version 2.
    • Indexing in place of slicing. Code such as lines[i] inside a loop up to n would raise IndexError when n is too big. The slice avoids the problem without any check.
    • Adding an unneeded guard. An if n > len(lines) branch is harmless but redundant here.
    • Expecting padding or an error. Neither happens: a too-big n is not an error, and the result is never longer than the input.

    Testing

    • ["alpha", "beta", "gamma"] with n = 10 gives 'alpha\nbeta\ngamma'.
    • ["a", "b", "c", "d", "e"] with n = 8 gives 'a\nb\nc\nd\ne'.
    • [] with n = 5 gives ''.
    • ["a", "b"] with n = 0 gives ''.

    The next version builds on this one.

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