Implement tail -n

Medium ⏱ 12 min 57% acceptance ★★★★★ 4.6
Write tail(path, n) returning the last n lines of a file as a list (stripped of trailing newlines). For this problem a simple read-all approach is fine — but keep only the last n using slicing, and handle files shorter than n gracefully.

Examples

Example 1
Input
tail('app.log', 2)  # file has lines a, b, c
Output
['b', 'c']
Explanation

The final two lines.

Constraints

  • Return at most n lines.
  • Shorter files return all their lines.

Topics

File Handlingtail

Companies

AmazonNetflixAkamai

Hints

Hint 1

f.read().splitlines() drops the newlines for you.

Hint 2

A negative slice [-n:] takes the tail.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.