# deque

In :
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 :
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 :
x = a.pop()
y = a.popleft()
a

Out:
deque([5, 6, 7, 8, 9])

Use rotate to rotate the deque in either direction.

In :
a.rotate(2)  # to the right
a

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

Out:
deque([5, 6, 7, 8, 9])

Use append to append items to either end.

In :
a.appendleft(0)
a.append(6)
a

Out:
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 :
a.extendleft([-3, -2, -1])  # items pushed off the right
a

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

Out:
deque([0, 5, 6, 7, 4, 5, 6])