PYTHON

Implementing a Fixed-Size History or Log with `collections.deque`

Efficiently manage a fixed-size collection of items like a browsing history or log with `collections.deque`, automatically discarding oldest entries.

from collections import deque

def create_fixed_size_history(max_size):
    return deque(maxlen=max_size)

history = create_fixed_size_history(3)
history.append('page1')
history.append('page2')
history.append('page3')
print(list(history)) # ['page1', 'page2', 'page3']
history.append('page4')
print(list(history)) # ['page2', 'page3', 'page4']
How it works: This snippet demonstrates how to use `collections.deque` to create a fixed-size history or log. When `maxlen` is specified, the deque automatically discards elements from the opposite end when new items are added, ensuring it never exceeds its maximum size. This is ideal for scenarios like recent activity feeds or limited browser history, offering efficient appends and pops from both ends.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs