In Python, you can add an item to the front of a deque (or double-ended queue) data structure using the appendleft()
method, for example, like so:
from collections import deque d = deque([1, 2, 3, 4]) d.appendleft(0) print(d) # deque([0, 1, 2, 3, 4])
This would add the number 0
to the left-most side (i.e. the front/start) of the deque.
In terms of time complexity, insertion to the front of a deque is a O(1)
operation.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.