If you want to keep a limited history of the last few items seen during iteration or other processes, you can use a deque which is a faster container, \(O(1)\), than a list, \(O(N)\). A deque allows you to keep a limited history of items, as in a queue.

from collections import deque
import numpy as np

d = deque(maxlen=3)
d.append(1)
d.append(2)
d.append("text")
d
## deque([1, 2, 'text'], maxlen=3)

If we add more items, the earlier ones get bumped.

d.append(4)
d.append("more text")
d
## deque(['text', 4, 'more text'], maxlen=3)

Here’s a hacky implementation of a loop that takes the mean of the most recent two items from a list.

numbers = [10, 25, 32, 49, 51, 63]

shortlist = deque(maxlen=2)

for i in numbers:
  shortlist.append(i)
  current = list(shortlist)
  print(np.mean(current))
## 10.0
## 17.5
## 28.5
## 40.5
## 50.0
## 57.0