deque

In [19]:
from collections import deque

A deque (or double-ended queue) is like a list, but supports efficient and convenient appends and pops at either end.

In [20]:
a = deque(range(11), maxlen=7)
print(a)
deque([4, 5, 6, 7, 8, 9, 10], maxlen=7)

Note that the maxlen parameter constrains the length of the deque and causes excess items to be pushed off the left.

Use pop to get items from either end.

In [21]:
x = a.pop()
y = a.popleft()
a
Out[21]:
deque([5, 6, 7, 8, 9])

Use rotate to rotate the deque in either direction.

In [22]:
a.rotate(2)  # to the right
a
Out[22]:
deque([8, 9, 5, 6, 7])
In [23]:
a.rotate(-2)  # to the left
a
Out[23]:
deque([5, 6, 7, 8, 9])

Use append to append items to either end.

In [24]:
a.appendleft(0)
a.append(6)
a
Out[24]:
deque([0, 5, 6, 7, 8, 9, 6])

Use extend to extend the deque in either directions using items from an iterable. The length of the deque remains unchanged and excess items are 'pushed off' from the opposite end.

In [25]:
a.extendleft([-3, -2, -1])  # items pushed off the right
a
Out[25]:
deque([-1, -2, -3, 0, 5, 6, 7])
In [26]:
a.extend([4, 5, 6])  # items pushed off the left
a
Out[26]:
deque([0, 5, 6, 7, 4, 5, 6])