0
0
PythonConceptBeginner · 3 min read

What is deque in Python: Explanation and Usage

In Python, a deque (double-ended queue) is a collection from the collections module that allows fast adding and removing of items from both ends. It works like a queue or stack but is more efficient for operations at the start and end of the list.
⚙️

How It Works

A deque is like a line of people where you can add or remove someone from the front or the back quickly. Imagine a queue at a store where people can join at the end or sometimes at the front if they have priority. This flexibility makes deque very useful.

Unlike a regular list, which can be slow when adding or removing items at the start because it has to move all other items, a deque is designed to handle these operations efficiently. It uses a special structure that keeps track of both ends, so adding or removing from either side is fast.

💻

Example

This example shows how to create a deque, add items to both ends, and remove items from both ends.

python
from collections import deque

# Create a deque
my_deque = deque([10, 20, 30])

# Add to the right end
my_deque.append(40)

# Add to the left end
my_deque.appendleft(5)

# Remove from the right end
right_item = my_deque.pop()

# Remove from the left end
left_item = my_deque.popleft()

print("Deque after operations:", my_deque)
print("Removed from right:", right_item)
print("Removed from left:", left_item)
Output
Deque after operations: deque([10, 20, 30]) Removed from right: 40 Removed from left: 5
🎯

When to Use

Use a deque when you need to add or remove items quickly from both ends of a collection. It is perfect for tasks like:

  • Implementing queues or stacks where you want to add or remove items from either end.
  • Managing a sliding window of data, such as recent events or measurements.
  • When performance matters and you want to avoid the slow operations of lists at the start.

For example, in a real-time chat app, you might use a deque to keep the last 100 messages, adding new ones at the end and removing old ones from the front efficiently.

Key Points

  • Deque stands for double-ended queue.
  • It allows fast adding/removing from both ends.
  • It is part of Python's collections module.
  • More efficient than lists for operations at the start.
  • Useful for queues, stacks, and sliding windows.

Key Takeaways

A deque allows fast adding and removing from both ends of a collection.
It is more efficient than lists for operations at the start of the sequence.
Deque is part of Python's collections module and easy to use.
Use deque for queues, stacks, and managing recent data efficiently.
Deque operations include append, appendleft, pop, and popleft.