Python Practice › Collections Programs › Program 10
Keep the last N items
Write a Python program that keeps only the 3 most recent log lines.
Output
['log 4', 'log 5', 'log 6']
Approach
deque(maxlen=3)drops the oldest automatically.
Solution
from collections import deque recent = deque(maxlen=3)for i in range(1, 7): recent.append(f"log {i}")print(list(recent))Output
['log 4', 'log 5', 'log 6']
Learn the concept
New to this topic? Read the lesson, then come back.