Pybites Logo Rust Platform

head & tail: First and Last N Lines

Easy +2 pts

🎯 head prints the first few lines of its input; tail prints the last few. They're mirroring each other, so we'll build both.

In Python you'd slice from each end:

def head(text, n):
    return text.splitlines()[:n]

def tail(text, n):
    return text.splitlines()[-n:]

That slice materializes the whole list first. Both languages can avoid it. Python with islice(lines, n), Rust with .take(n), because head is allowed to stop early. tail isn't: you can't know where the end is until you've seen every line. That asymmetry (not the language) is …

Login to see the full exercise.