Deque
Deque stands for double-ended queue.
Difference
Though
list
objects support similar operations, they are optimized for fast fixed-length operations and incur \(O(n)\) memory movement costs forpop(0)
andinsert(0, v)
operations which change both the size and position of the underlying data representation.
Example
>>> from collections import deque
>>> d = deque('ghi') # make a new deque with three items
>>> for elem in d: # iterate over the deque's elements
... print(elem.upper())
G
H
I
>>> d.append('j') # add a new entry to the right side
>>> d.appendleft('f') # add a new entry to the left side
>>> d # show the representation of the deque
deque(['f', 'g', 'h', 'i', 'j'])
>>> d.pop() # return and remove the rightmost item
'j'
>>> d.popleft() # return and remove the leftmost item
'f'