A deque
(short for “double-ended queue”) is a data structure from the collections
module in Python that allows you to add and remove elements from both ends efficiently. It is a versatile and high-performance alternative to lists for certain use cases, especially when you need fast appends and pops from both ends of the queue.
1. Importing deque
To use deque
, you first need to import it from the collections
module:
from collections import deque
2. Creating a Deque
You can create a deque
by passing an iterable (e.g., a list) to the deque
constructor:
# Creating an empty deque
dq = deque()
# Creating a deque with initial elements
dq = deque([1, 2, 3, 4, 5])
3. Adding and Removing Elements
deque
supports efficient appends and pops from both ends of the queue.
3.1 Appending Elements
# Appending elements to the right
dq.append(6)
# Appending elements to the left
dq.appendleft(0)
3.2 Removing Elements
# Removing elements from the right
dq.pop()
# Removing elements from the left
dq.popleft()
3.3 Example
from collections import deque
# Create a deque with initial elements
dq = deque([1, 2, 3])
# Append elements
dq.append(4) # deque([1, 2, 3, 4])
dq.appendleft(0) # deque([0, 1, 2, 3, 4])
# Remove elements
dq.pop() # deque([0, 1, 2, 3])
dq.popleft() # deque([1, 2, 3])
4. Rotating the Deque
deque
also provides a method to rotate the elements. Positive values rotate the deque to the right, while negative values rotate it to the left:
# Rotating right by 2 steps
dq.rotate(2)
# Rotating left by 3 steps
dq.rotate(-3)
5. Accessing Elements
You can access elements in a deque
using indexing, just like with a list:
# Accessing elements
element = dq[0] # First element
last_element = dq[-1] # Last element
6. Using Deque as a Queue
The deque
is ideal for implementing queues where you need to efficiently add and remove elements from both ends:
from collections import deque
# Initialize deque
queue = deque()
# Enqueue (append) elements
queue.append('A')
queue.append('B')
# Dequeue (pop) elements
item = queue.popleft() # 'A'
7. Summary
The deque
from the collections
module is a flexible and efficient data structure for adding and removing elements from both ends. It supports operations like appending, popping, and rotating, making it a powerful tool for various applications where such operations are frequent.