The deque
(double-ended queue) is a part of Python's collections
module and provides a generalization of stacks and queues. deque
is optimized for fast fixed-length operations at both ends and can be used where fast append and pop operations are required.
deque
A deque
is created using the collections.deque
class. It can take an iterable as an argument to initialize the deque with elements.
from collections import deque
d = deque([1, 2, 3])
empty_deque = deque() # Create an empty deque
deque
deque
supports bounded lengths, which means you can create a deque with a maximum length and when the deque is full, appending another element automatically removes one from the opposite end.deque
deque
Operationsappend(item)
: Add an element to the right end of the deque.
d.append(4) # deque([1, 2, 3, 4])
appendleft(item)
: Add an element to the left end of the deque.
d.appendleft(0) # deque([0, 1, 2, 3, 4])
pop()
: Remove and return an element from the right end of the deque.
d.pop() # 4, deque becomes deque([0, 1, 2, 3])
popleft()
: Remove and return an element from the left end of the deque.
d.popleft() # 0, deque becomes deque([1, 2, 3])
extend(iterable)
: Extend the deque by appending elements from the iterable to the right end.
d.extend([4, 5]) # deque([1, 2, 3, 4, 5])
extendleft(iterable)
: Extend the deque by appending elements from the iterable to the left end (note that the iterable is reversed).
d.extendleft([0, -1]) # deque([-1, 0, 1, 2, 3, 4, 5])
rotate(n)
: Rotate the deque n steps to the right. If n is negative, rotate to the left.
d.rotate(2) # deque([4, 5, -1, 0, 1, 2, 3])
d.rotate(-2) # deque([-1, 0, 1, 2, 3, 4, 5])
Indexing: Access elements by their index.
first_element = d[0] # -1
count(item)
: Count the number of occurrences of an item in the deque.
count = d.count(1) # 1
remove(value)
: Remove the first occurrence of the value in the deque. Raises a ValueError
if the value is not present.
d.remove(1) # deque([-1, 0, 2, 3, 4, 5])
deque
Methodsclear()
: Remove all elements from the deque.
d.clear() # deque([])
copy()
: Return a shallow copy of the deque (available in Python 3.5+).
d_copy = d.copy() # deque([-1, 0, 2, 3, 4, 5])
reverse()
: Reverse the elements of the deque in place.
d.reverse() # deque([5, 4, 3, 2, 0, -1])
rotate()
can lead to inefficient code if not used carefully, as it involves shifting all elements.extendleft()
: The extendleft()
method adds elements in reverse order from the given iterable, which may lead to unexpected results if not handled properly.
d = deque([1, 2, 3])
d.extendleft([4, 5]) # deque([5, 4, 1, 2, 3])
deque
queue
module): If you need thread-safe queues, consider using queue.Queue
, queue.LifoQueue
, or queue.PriorityQueue
.This comprehensive guide should help you understand Python deque
, its features, and best practices for using it effectively in your programs.