Wrapping around a list in Python.

Peter Otten __peter__ at web.de
Mon Dec 16 04:15:48 EST 2013


shengjie.shengjie at live.com wrote:

> The idea is to grab the last 4 elements of the array. However i have an
> array that contains a few hundred elements in it. And the values continues
> to .append over time. How would i be able to display the last 4 elements
> of the array under such a condition?

Use a deque:

>>> from collections import deque
>>> last_four = deque(maxlen=4)
>>> for i in range(10):
...     last_four.append(i)
... 
>>> last_four
deque([6, 7, 8, 9], maxlen=4)
>>> last_four.extend(range(100, 200))
>>> last_four
deque([196, 197, 198, 199], maxlen=4)
>>> last_four.append(42)
>>> last_four
deque([197, 198, 199, 42], maxlen=4)





More information about the Python-list mailing list