Skip to content

14. Keep the Last N Events

Difficulty: Medium · Topic: Core Python & data structures

Write last_n(events, n): return the last n items of events as a list, oldest first.

Your code runs in CPython on our servers against 5 tests, including hidden ones.

Sample test

last_n(['a', 'b', 'c', 'd', 'e'], 3)

Expected: ['c', 'd', 'e']

Hints

Hint 1A generator cannot be sliced, and list(events) would hold the whole log.
Hint 2collections.deque(iterable, maxlen=n) keeps only the newest n items: adding one more drops the oldest.
Hint 3Watch n = 0: xs[-0:] is the whole list, because -0 is 0.

Learn the concepts

More Python problems

All Python problems