Deque

A deque is a doubly linked list. It has O(1) appends and pops on either end, and can optionally be provided with a maximum size on construction.

In exchange, random access costs you O(n).

Initialization

from collections import deque

empty = deque() # empty deque
de = deque([1,2,3]) # unlimited size deque.
limited = deque([1,2,3], 3) # limited to size 3.

Methods

d = deque([1,2,3,4]) # [1,2,3,4]
d.append(5) # [1,2,3,4,5]
d.appendleft(0) # [0,1,2,3,4,5]
d.count(1) # 1 | count of all elements equal to 1.
d.extend([6,7]) # [0,1,2,3,4,5,6,7] | add iterable to end
d.extend([-2,-1]) # [-2,-1,0,1,2,3,4,5,6,7] | add iterable to beginning
d.pop() # 7 | [-2,-1,0,1,2,3,4,5,6] | remove from end and return
d.popleft() # -2 [-1,0,1,2,3,4,5,6] | remove from beginning and return
d.remove(0) # | [-1,1,2,3,4,5,6] | removes first 0.
d.reverse() # reverse in place
d.rotate(1) # rotate in place to the right.
d.clear() # remove all elements