Keep the last N items

EasyCollections Programs · 10 of 20

Write a Python program that keeps only the 3 most recent log lines.

Advertisement
Output
['log 4', 'log 5', 'log 6']

Approach

  1. deque(maxlen=3) drops the oldest automatically.

Solution

Python
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.

More collections programs

← All 20 Collections Programs

Leave a Comment