Last Updated on 2021-10-09 by Clay
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 queueappendleft()
: Add element to the left of the queuepop()
: Pop element of the right of the queuepopleft()
: 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
- https://www.geeksforgeeks.org/deque-in-python/
- https://www.tutorialspoint.com/python/python_deque.htm
- https://pymotw.com/2/collections/deque.html