Skip to content

[Python] How To Use Doubly Ended Queue (Deque)

Deque (Doubly Ended Queue) is a classic data structure, and it is implemented as a module collections in Python.

It is different with Python List, deque can operate on both ends of the queue. In addition, List can only use O(n) time complexity to insert element in beginning, but deque can use O(1).

Here are the most important functions in deque:

  • append(): Add element to the right of the queue
  • appendleft(): Add element to the left of the queue
  • pop(): Pop element of the right of the queue
  • popleft(): Pop element of the left of the queue

The method of use is as follows.


How To Use Deque

Let’s use the sample code to see the effects of different functions.

# coding: utf-8
from collections import deque


def main():
    q = deque([5, 6, 7])

    # append()
    q.append(8)
    print('After append(8):', q)

    # pop()
    q.pop()
    print('After pop():', q)

    # appendleft()
    q.appendleft(4)
    print('After appendleft(4):', q)

    # popleft()
    q.popleft()
    print('After popleft():', q)


if __name__ == '__main__':
    main()


Output:

After append(8): deque([5, 6, 7, 8])
After pop(): deque([5, 6, 7])
After appendleft(4): deque([4, 5, 6, 7])
After popleft(): deque([5, 6, 7])


The above is the basic method to use deque in Python.


References


Read More

Tags:

Leave a Reply