Ben Chuanlong Du's Blog

It is never too late to learn.

Hands on the Deque Collection in Python

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

Tips and Traps

  1. A deque is implemented via the circular queue data structure and it has O(1) time complexity appending from both ends.

  2. Unlike list and tuple collections, a deque CANNOT be sliced!

In [1]:
from collections import deque
In [3]:
q = deque()
q.appendleft(36)
q.appendleft(25)
q.appendleft(9)
q
Out[3]:
deque([9, 25, 36])

Unlike list and tuple collections, deque CANNOT be sliced!

In [5]:
q[1:]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/workspace/blog/misc/content/2022/03/hands-on-the-deque-collection-in-python/hands-on-the-deque-collection-in-python.ipynb Cell 7' in <cell line: 1>()
----> <a href='vscode-notebook-cell://dclong-blog-nymhodme885.ws-us34.gitpod.io/workspace/blog/misc/content/2022/03/hands-on-the-deque-collection-in-python/hands-on-the-deque-collection-in-python.ipynb#ch0000007vscode-remote?line=0'>1</a> q[1:]

TypeError: sequence index must be integer, not 'slice'
In [ ]:
 

Comments