The collections.deque
class in Python’s collections
module provides a double-ended queue with efficient appends and pops from both ends. It is a useful data structure for tasks that require fast access and modification of elements at both ends of the queue.
Table of Contents
- Introduction
collections.deque
Class Syntax- Examples
- Basic Usage
- Adding and Removing Elements
- Accessing Elements
- Using
maxlen
to Limit the Size of the Deque - Rotating Elements
- Real-World Use Case
- Conclusion
Introduction
The collections.deque
class in Python’s collections
module provides a double-ended queue that supports thread-safe, memory-efficient appends and pops from both ends. This makes it an ideal choice for implementing queues, stacks, and other similar data structures.
collections.deque Class Syntax
Here is how you use the collections.deque
class:
from collections import deque
dq = deque(iterable=None, maxlen=None)
Parameters:
iterable
: Optional. An initial iterable to populate the deque.maxlen
: Optional. The maximum length of the deque. If not specified, the deque can grow to an arbitrary length.
Returns:
- A new deque object.
Examples
Basic Usage
Here is an example of how to create and use a deque to store a sequence of integers.
Example
from collections import deque
# Creating a deque
dq = deque([1, 2, 3, 4, 5])
print(dq)
Output:
deque([1, 2, 3, 4, 5])
Adding and Removing Elements
You can add elements to both ends of the deque using append
and appendleft
, and remove elements using pop
and popleft
.
Example
from collections import deque
# Creating a deque
dq = deque([1, 2, 3])
# Adding elements to the right end
dq.append(4)
dq.append(5)
# Adding elements to the left end
dq.appendleft(0)
dq.appendleft(-1)
# Removing elements from both ends
right_end = dq.pop()
left_end = dq.popleft()
print(dq)
print(f"Removed from right end: {right_end}")
print(f"Removed from left end: {left_end}")
Output:
deque([0, 1, 2, 3, 4])
Removed from right end: 5
Removed from left end: -1
Accessing Elements
You can access elements in the deque using indexing and slicing.
Example
from collections import deque
# Creating a deque
dq = deque(['a', 'b', 'c', 'd', 'e'])
# Accessing elements by index
first_element = dq[0]
last_element = dq[-1]
# Slicing the deque
middle_elements = list(dq)[1:4]
print(f"First element: {first_element}")
print(f"Last element: {last_element}")
print(f"Middle elements: {middle_elements}")
Output:
First element: a
Last element: e
Middle elements: ['b', 'c', 'd']
Using maxlen
to Limit the Size of the Deque
You can limit the size of the deque using the maxlen
parameter. When the deque reaches its maximum length, the oldest elements are automatically removed when new elements are added.
Example
from collections import deque
# Creating a deque with a maximum length of 3
dq = deque(maxlen=3)
# Adding elements
dq.append(1)
dq.append(2)
dq.append(3)
dq.append(4) # The deque is now [2, 3, 4] and 1 is removed
print(dq)
Output:
deque([2, 3, 4], maxlen=3)
Rotating Elements
You can rotate the elements in the deque to the right or left using the rotate
method.
Example
from collections import deque
# Creating a deque
dq = deque([1, 2, 3, 4, 5])
# Rotating elements to the right by 2
dq.rotate(2)
# Rotating elements to the left by 1 (negative value)
dq.rotate(-1)
print(dq)
Output:
deque([5, 1, 2, 3, 4])
Real-World Use Case
Implementing a Simple Task Scheduler
In real-world applications, the collections.deque
class can be used to implement a simple task scheduler where tasks are processed in the order they are added, with the ability to add and remove tasks efficiently from both ends.
Example
from collections import deque
class TaskScheduler:
def __init__(self):
self.tasks = deque()
def add_task(self, task):
self.tasks.append(task)
print(f"Task added: {task}")
def process_task(self):
if self.tasks:
task = self.tasks.popleft()
print(f"Processing task: {task}")
else:
print("No tasks to process")
# Example usage
scheduler = TaskScheduler()
scheduler.add_task("Task 1")
scheduler.add_task("Task 2")
scheduler.add_task("Task 3")
scheduler.process_task()
scheduler.process_task()
scheduler.process_task()
scheduler.process_task()
Output:
Task added: Task 1
Task added: Task 2
Task added: Task 3
Processing task: Task 1
Processing task: Task 2
Processing task: Task 3
No tasks to process
Conclusion
The collections.deque
class in Python’s collections
module provides a double-ended queue that supports fast, memory-efficient operations for adding and removing elements from both ends. This class is useful for implementing various data structures and algorithms that require efficient access and modification of elements at both ends of the queue. Proper usage of this class can enhance the performance and readability of your code.