Home > Article > Backend Development > How to use deque to retain the latest N elements in python (code)
The content of this article is about the implementation method (code) of using deque to retain the latest N elements in Python. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. .
1. Requirements
Make a limited number of historical records.2. Solution
deque(maxlen=N), create a fixed-length queue, and when new records are added and the queue is full, the oldest record will be automatically removed. .Code:
from collections import deque q=deque(maxlen=3) q.append(1) q.append(2) q.append(3) print(q) q.append(4) print(q) q.append(5) print(q)
Result:
deque([1, 2, 3], maxlen=3) deque([2, 3, 4], maxlen=3) deque([3, 4, 5], maxlen=3)
If you do not specify the size of the queue, you will get an unbounded queue, and you can perform add and pop operations at both ends,
Code:
from collections import deque q=deque() q.append(1) q.append(2) q.append(3) q.append(4) print(q) q.appendleft(5) print(q) print(q.pop()) print(q) print(q.popleft()) print(q)
Result:
deque([1, 2, 3, 4]) deque([5, 1, 2, 3, 4]) 4 deque([5, 1, 2, 3]) 5 deque([1, 2, 3])
The above is the detailed content of How to use deque to retain the latest N elements in python (code). For more information, please follow other related articles on the PHP Chinese website!