Start learning free

LESSON 6 OF 68 · PROJECTS: COMMAND-LINE TOOLS

head v2 in Python: First n Lines with lines[:n]

Practice Read the full explanation

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

    PYTHON · PROJECTS: COMMAND-LINE TOOLS

    Head V2 in Python, explained

    Problem overview

    Version 1 of this head project always kept 10 lines. In this version the method takes the count as a second argument: head(self, lines, n) returns the first n lines, joined with newline characters (\n). For this version, n is between 0 and len(lines), so there is no need to handle a count that is too big or negative. When n is 0, the result is an empty string.

    For ["alpha", "beta", "gamma", "delta", "epsilon"] and n = 3, the result is 'alpha\nbeta\ngamma', which prints as:

    alpha
    beta
    gamma
    

    Approach: replace the constant with n

    The idea is the one from version 1, with the fixed 10 replaced by the variable n. A slice from the start, lines[:n], holds the items at indexes 0 up to but not including n, which is exactly the first n lines. Joining that slice with "\n" gives the result.

    The special case takes care of itself. With n = 0, the slice lines[:0] is an empty list, and joining an empty list gives ''. No if is needed, and no loop either: the slice does the counting and the join does the gluing.

    Step by step

    The lesson has a single step. The method now has two parameters besides self, lines and n, and it returns "\n".join(lines[:n]). The only change from the previous version is that the slice's end is the parameter and no longer the number 10.

    The solution in Python

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

    What to know about it:

    • A slice end can be any expression. A variable works the same as a literal number, so lines[:n] and lines[:3] behave alike when n is 3.
    • The count is the number of items kept. lines[:3] holds items 0, 1 and 2, so three lines come back, and the item at index 3 is left out.
    • The slice is a copy. lines keeps all its items after the call.
    • The method has the same name as in version 1, with a different signature. Each lesson defines its own Solution class, so the two versions don't conflict. Python itself has no overloading: a second def head in the same class would replace the first.

    Edge cases and common mistakes

    • n = 0. The result is ''. For ["a", "b"] and n = 0, the slice is empty, so nothing is joined.
    • n equal to the length. All lines come back: head(["a", "b"], 2) returns 'a\nb'.
    • Using lines[n] or lines[n - 1]. Those are single items, not the first n. The colon makes it a slice.
    • Writing lines[:n - 1] to "fix" the counting. Indexes start at 0, but a slice end already excludes its own position, so [:n] is already right. With n = 3, lines[:2] would return only two lines.
    • Looping and adding a newline after every line. That leaves a newline at the end of the result. join puts the separator only between lines.
    • Mixing up the argument order. The signature is head(lines, n): the list first, then the count.

    Testing

    • ["alpha", "beta", "gamma", "delta", "epsilon"] with n = 3 gives 'alpha\nbeta\ngamma'.
    • ["a", "b"] with n = 0 gives ''.
    • ["a", "b"] with n = 2 gives 'a\nb'.

    The next version builds on this one.

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