How to use a deque in Python

widget

A deque is a double-ended queue in which elements can be both inserted and deleted from either the left or the right end of the queue. An implementation of a deque in Python is available in the collections module.

Below is a brief description of the methods used to modify a deque:

Insertion

append(item): Add an item to the right end.

appendleft(item): Add an item to the left end.

insert(index, value): Add an element with the specified value at the given index.

extend(list): This function is used to insert multiple values at the right end. It takes a list of values as an argument.

extendleft(list): This function is similar to extend(), but it reverses the list of values passed as the argument and then appends that list to the left end of the deque.

Deletion

pop(): Remove an element from the right end.

popleft(): Remove an element from the left end.

remove(value): Remove the first occurrence of the mentioned value.

Miscellaneous

count(value): Return the total number of occurrences of the given value.

index(e, start, end): Search the given element from start to finish​ and return the index of the first occurrence.

rotate(n): Rotate the deque nn number of times. A positive value rotates it to the right, while a negative value rotates it to the left.

reverse(): Reverse the order of the deque.

Demo

1 of 19

Code

# Import collections module:
import collections
# Initialize deque:
dq = collections.deque([4, 5, 6])
# Append to the right:
dq.append(7)
print("Append 7 to the right: ", list(dq))
# Append to the left:
dq.appendleft(3)
print("Append 3 to the left: ", list(dq))
# Append multiple values to right:
dq.extend([8, 9, 10])
print("Append 8, 9 and 10 to the right: ", list(dq))
# Append multiple values to left:
dq.extendleft([1, 2])
print("Append 2 and 1 to the left: ", list(dq))
# Insert -1 at index 5
dq.insert(5, -1)
print("Insert -1 at index 5: ", list(dq))
# Pop element from the right end:
dq.pop()
print("Remove element from the right: ", list(dq))
# Pop element from the left end:
dq.popleft()
print("Remove element from the left: ", list(dq))
# Remove -1:
dq.remove(-1)
print("Remove -1: ", list(dq))
# Count the number of times 5 occurs:
i = dq.count(5)
print("Count the number of times 5 occurs: ", i)
# Return index of '7' if found between index 4 and 6:
i = dq.index(7, 4, 6)
print("Search index of number 7 between index 4 and 6: ", i)
# Rotate the deque three times to the right:
dq.rotate(3)
print("Rotate the deque 3 times to the right: ", list(dq))
# Reverse the whole deque:
dq.reverse()
print("Reverse the deque: ", list(dq))
Copyright ©2024 Educative, Inc. All rights reserved