What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More
Computer Science

Python Deque (collections.deque) with Examples

Jul 18, 2026 4 Minutes Read Why Trust Us Why you can trust this guide. Written by working engineers and reviewed by our editorial team under a strict editorial policy for accuracy, clarity and zero bias. Abrar Ahmed By Abrar Ahmed Abrar Ahmed Abrar Ahmed
An ambivert individual with a thirst for knowledge and passion to achieve. Striving to connect Artificial Intelligence in all aspects of life. I am also an avid coder and partake in coding challenges all the time on Leetcode and CodeChef.
Connect on LinkedIn →
Python Deque (collections.deque) with Examples

In Python, a deque is a double ended queue from the collections module. It supports adding and removing elements from both ends in O(1) constant time, which a regular list cannot do.

That speed at both ends is the whole point: deques power queues, sliding windows, and any structure where elements enter one side and leave the other.

What Is a Deque in Python?

A deque (pronounced "deck", short for double ended queue) is a list-like container optimized for fast appends and pops at either end. A regular list removes its first element in O(n) time, because every remaining element shifts one place left. A deque does the same job in O(1), no shifting, at the cost of slower access to elements in the middle.

The spelling matters when searching: "dequeue" with two u's is the verb for removing from a queue, while the Python type is spelled deque.

A deque open at both ends with appendleft and popleft on the left and append and pop on the right, all O(1)

How to Import Deque in Python

Deque lives in the standard library's collections module, so no installation is needed:

from collections import deque

q = deque(["riya", "sam", "leo"])
print(q)  # Outputs: deque(['riya', 'sam', 'leo'])

Creating a Deque

The deque() constructor accepts any iterable, or nothing for an empty deque. The optional maxlen argument caps its length, and a full deque silently drops elements from the opposite end when new ones arrive:

from collections import deque

empty = deque()
letters = deque("abc")
recent = deque([1, 2, 3], maxlen=3)

recent.append(4)   # 1 falls off the left
print(recent)  # Outputs: deque([2, 3, 4], maxlen=3)

Python Deque Methods

The four core methods cover both ends. append() and pop() work on the right, and their left twins work on the left:

from collections import deque

tasks = deque(["review", "deploy"])
tasks.append("email")        # add on the right
tasks.appendleft("standup")  # add on the left
print(tasks)
# Outputs: deque(['standup', 'review', 'deploy', 'email'])

print(tasks.popleft())  # Outputs: standup
print(tasks.pop())      # Outputs: email
print(tasks)            # Outputs: deque(['review', 'deploy'])
MethodWhat it does
append(x)Adds x to the right end
appendleft(x)Adds x to the left end
pop()Removes and returns the rightmost element
popleft()Removes and returns the leftmost element
extend(iter)Appends each element to the right
extendleft(iter)Appends each element to the left, reversing their order
rotate(n)Shifts all elements n steps to the right (negative n goes left)
count(x)Counts occurrences of x
remove(x)Removes the first occurrence of x
reverse()Reverses the deque in place
clear()Removes every element

len() returns the current size, and the maxlen attribute holds the cap, or None when the deque is unbounded.

When to Use a Deque

Reach for a deque whenever elements leave from the front. The comparison with a list makes the trade clear:

OperationListDeque
Append at the rightO(1) amortizedO(1)
Remove from the leftO(n), every element shiftsO(1)
Add at the leftO(n)O(1)
Index access in the middleO(1)O(n)

Queues and stacks are the classic cases, covered in the stacks and queues lesson. When your code mostly reads elements by index, a list remains the right container.

Examples of Using Deque in Python

1) A Queue with append() and popleft()

Elements join at the right and leave from the left, first in, first out:

from collections import deque

waiting = deque()
waiting.append("riya")
waiting.append("sam")
waiting.append("leo")

print(waiting.popleft())  # Outputs: riya
print(waiting.popleft())  # Outputs: sam

2) Keeping Only the Last N Items

A maxlen deque is a rolling window: append forever, and it keeps just the newest entries. Here it tracks the last three log lines:

from collections import deque

log = deque(maxlen=3)
for line in ["boot", "connect", "sync", "upload", "done"]:
    log.append(line)

print(log)  # Outputs: deque(['sync', 'upload', 'done'], maxlen=3)
A maxlen three deque where appending a new element pushes the oldest one out of the window

3) Rotating Elements

rotate() moves elements from one end to the other, which cycles through turns in a game or shifts a schedule:

from collections import deque

players = deque(["riya", "sam", "leo"])
players.rotate(-1)   # first player moves to the back
print(players)  # Outputs: deque(['sam', 'leo', 'riya'])

Learn More About Python Deque

Deque vs queue.Queue

The standard library also has queue.Queue, which adds locking so multiple threads can share it safely. For single-threaded code, deque is simpler and faster; queue.Queue earns its overhead only when threads hand work to each other.

Where Deque Comes From

CPython implements deque as a doubly linked list of fixed-size blocks, which is why both ends are O(1) and middle indexing is O(n). The same trade appears in graph algorithms: breadth first search uses a deque as its frontier queue precisely because popleft() stays fast at any size.

Key Takeaways for Python Deque

  • Import first - from collections import deque; it is standard library, nothing to install.
  • O(1) at both ends - append(), appendleft(), pop(), and popleft() never shift elements.
  • Lists lose at the front - list.pop(0) is O(n); switch to a deque when elements leave from the left.
  • maxlen makes a rolling window - The deque drops old elements automatically once full.
  • rotate() cycles - Elements wrap from one end to the other in either direction.
  • Deque, not dequeue - The type is deque; "dequeue" is the act of removing from a queue.

The most common real use of a deque is the frontier queue in breadth first search, where its O(1) popleft() keeps the whole traversal fast.

Abrar Ahmed
About the author

Abrar Ahmed

An ambivert individual with a thirst for knowledge and passion to achieve. Striving to connect Artificial Intelligence in all aspects of life. I am also an avid coder and partake in coding challenges all the time on Leetcode and CodeChef. Connect on LinkedIn →