How to Add a Value to the Front of a deque in Python?

Find out how to add a value to the start of a Python deque data structure

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.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.