Stats

92 Contributors: 7 Monday, November 7, 2016
Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Rip Tutorial: riptutorial@gmail.com
Roadmap: roadmap

Deque Module

Syntax

  • dq = deque() # Creates an empty deque
  • dq = deque(iterable) # Creates a deque with some elements
  • dq.append(object) # Adds object to the right of the deque
  • dq.appendleft(object) # Adds object to the left of the deque
  • dq.pop() -> object # Removes and returns the right most object
  • dq.popleft() -> object # Removes and returns the left most object
  • dq.extend(iterable) # Adds some elements to the right of the deque
  • dq.extendleft(iterable) # Adds some elements to the left of the deque

Parameters

ParameterDetails
iterableCreates the deque with initial elements copied from another iterable.
maxlenLimits how large the deque can be, pushing out old elements as new are added.

Remarks

This class is useful when you need an object similar to a list that allows fast append and pop operations from either side (the name deque stands for “double-ended queue”).

The methods provided are indeed very similar, except that some like pop, append, or extend can be suffixed with left. The deque data structure should be preferred to a list if one needs to frequently insert and delete elements at both ends because it allows to do so in constant time O(1).

Related Examples