Exercise 2 solution from collections import deque def last_n(lines, n): buf = deque(maxlen=n) for item in lines: buf.append(item) return list(buf) print(last_n(range(10), 3)) print(last_n([1, 2], 5)) print(last_n(range(10), 1)) Output: [7, 8, 9] [1, 2] [9] The deque never holds more than n items: once full, each append drops the oldest item from the other end. So this works on a huge or endless-looking stream without storing it all. list.pop(0) removes the first item, and every remaining item must then shift one place left, so each removal costs work proportional to the length of the list. Draining a long list this way repeats that shifting many times over. deque.popleft() removes from the front without moving the other items, so each removal is a constant amount of work.