deque
  • a double-ended queue, or deque, supports adding and removing elements from either end of the queue
  • a mutable, sequential data structure
  • Initialization
    from collections import deque
    
    a = deque('abcdefg') #deque(['a', 'b', 'c', 'd', 'e', 'f', 'g'])
    print(a)
    b = deque(['Hello', 2]) # deque(['Hello', 2])
    print(len(b))
    			
    Access
    print(a[0]) # a
    a[0] = 'h' # deque(['h', 'b', 'c', 'd', 'e', 'f', 'g'])
                
    Methods
    d = deque('abcdefg')
    
    # append, add a new entry to the right side
    d.append('j') # deque(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'j'])
    
    # appendleft, add a new entry to the left side
    d.appendleft('f') # deque(['f', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'j'])
    
    # pop
    print(d.pop()) # j, return and remove the rightmost item
    
    # popleft
    print(d.popleft()) # f, return and remove the leftmost item
    
    print(d) # deque(['a', 'b', 'c', 'd', 'e', 'f', 'g'])
    print(d[0]) # a, peek at leftmost item
    print(d[-1]) # g, peek at rightmost item
    
    # extend, add multiple elements at once
    d.extend(['Hello', 'World']) # deque(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'Hello', 'World'])
    
    # rotate
    d.rotate(3) # deque(['g', 'Hello', 'World', 'a', 'b', 'c', 'd', 'e', 'f']), right rotation
    d.rotate(-2) # deque(['World', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'Hello']), left rotation
    
    # clear, empty the deque
    d.clear()
                
    Built-in Functions
    b = deque(['Hello', 2]) # deque(['Hello', 2])
    print(len(b)) # 2
    
    l = list(b) # ['Hello', 2]
    print(l)
    
    list(reversed(b)) # [2, 'Hello']
    
    b = deque(reversed(b)) # deque([2, 'Hello']), make a new deque in reverse order
    print(b)
                
    Reference
  • Python 3 Standard Library
  • Python 3 Module of the Week