Skip to content

Python Deque: Effortlessly Manage Double-Ended Queues

[

Python’s deque: Implement Efficient Queues and Stacks

Python’s deque is a powerful data type in the collections module that provides a fast and memory-efficient way to append and pop items from both ends of a list-like data structure. In this tutorial, you will learn how to use Python’s deque to implement efficient queues and stacks.

Getting Started With Python’s deque

When working with Python lists, appending and popping items on the right end is efficient, with a time complexity of O(1). However, appending and popping items on the left end of a list can be inefficient, with a time complexity of O(n) when the list needs to reallocate memory. Python’s deque solves this problem by providing efficient ways to append and pop items from both ends of the underlying data structure.

To get started with Python’s deque, you need to import the collections module and create a new deque object. Here’s an example:

from collections import deque
mydeque = deque()

Popping and Appending Items Efficiently

To append an item to the right end of a deque, you can use the .append() method. Similarly, to append an item to the left end of a deque, you can use the .appendleft() method. Here’s an example:

mydeque.append(1)
mydeque.appendleft(2)

Similarly, you can use the .pop() and .popleft() methods to remove and return items from the right and left ends of a deque, respectively. Here’s an example:

item = mydeque.pop()
left_item = mydeque.popleft()

Accessing Random Items in a deque

Unlike lists, deques don’t support direct indexing. However, you can use the .index() method to find the index of an item in a deque. Here’s an example:

index = mydeque.index(1)

Building Efficient Queues With deque

Python’s deque is an excellent choice for implementing queues because it provides efficient ways to append and pop items from both ends. To enqueue an item, you can use the .append() method, and to dequeue an item, you can use the .popleft() method. Here’s an example:

myqueue = deque()
myqueue.append("item1")
myqueue.append("item2")
item = myqueue.popleft()

Exploring Other Features of deque

Python’s deque provides additional features that can be useful in different scenarios.

Limiting the Maximum Number of Items: maxlen

You can limit the number of items in a deque by specifying a maximum length using the maxlen parameter. When the deque reaches this maximum length, adding new items will automatically remove items from the opposite end. Here’s an example:

mydeque = deque(maxlen=3)
mydeque.append(1)
mydeque.append(2)
mydeque.append(3)
mydeque.append(4)
print(mydeque) # Output: deque([2, 3, 4], maxlen=3)

Rotating the Items: .rotate()

The .rotate() method allows you to rotate the items in a deque by a specified number of steps. Positive numbers rotate the items to the right, and negative numbers rotate the items to the left. Here’s an example:

mydeque = deque([1, 2, 3, 4, 5])
mydeque.rotate(2)
print(mydeque) # Output: deque([4, 5, 1, 2, 3])

Adding Several Items at Once: .extendleft()

The .extendleft() method allows you to add multiple items to the left end of a deque efficiently. Here’s an example:

mydeque = deque([1, 2, 3])
mydeque.extendleft([4, 5, 6])
print(mydeque) # Output: deque([6, 5, 4, 1, 2, 3])

Using Sequence-Like Features of deque

Python’s deque supports many sequence-like features, such as iteration, slicing, and concatenation. Here are some examples:

mydeque = deque([1, 2, 3, 4, 5])
# Iteration
for item in mydeque:
print(item)
# Slicing
sliced_deque = mydeque[:3]
print(sliced_deque) # Output: deque([1, 2, 3])
# Concatenation
concatenated_deque = mydeque + deque([6, 7, 8])
print(concatenated_deque) # Output: deque([1, 2, 3, 4, 5, 6, 7, 8])

Putting Python’s deque Into Action

Now that you have learned the basics of using Python’s deque, let’s explore some common use cases where deque can be particularly useful.

Keeping a Page History

You can use a deque to keep track of a user’s page history with a limited number of items. When a new page is visited, you can use the .append() method to add it to the right end of the deque. If the maximum number of items is reached, the oldest item will automatically be removed from the left end. Here’s an example:

page_history = deque(maxlen=5)
page_history.append("Page 1")
page_history.append("Page 2")
page_history.append("Page 3")
page_history.append("Page 4")
page_history.append("Page 5")
page_history.append("Page 6")
print(page_history) # Output: deque(['Page 2', 'Page 3', 'Page 4', 'Page 5', 'Page 6'], maxlen=5)

Sharing Data Between Threads

deque is thread-safe and can be safely used to share data between multiple threads. You can use the .append() and .popleft() methods to add and remove items from a deque safely. Here’s an example:

from collections import deque
from threading import Thread
def worker(id, data):
for item in data:
print(f"Worker {id}: {item}")
data.popleft()
mydeque = deque([1, 2, 3, 4, 5])
# Create two worker threads
thread1 = Thread(target=worker, args=(1, mydeque))
thread2 = Thread(target=worker, args=(2, mydeque))
# Start the threads
thread1.start()
thread2.start()
# Wait for the threads to finish
thread1.join()
thread2.join()

Emulating the tail Command

The .rotate() method can be used to emulate the behavior of the tail command in Unix-like systems. By rotating a deque with a negative number of steps, you can efficiently access the last few items of a larger sequence. Here’s an example:

def tail(file, n=10):
with open(file) as f:
last_lines = deque(f, n)
for line in last_lines:
print(line, end='')
tail("logfile.txt")

Conclusion

Python’s deque is a powerful and efficient data type that provides a wide range of functionalities for implementing queues and stacks. In this tutorial, you learned how to use Python’s deque to append and pop items efficiently, build efficient queues, explore other features of deque, use sequence-like features, and put deque into action in various use cases. By leveraging the features of deque, you can make your code more efficient and Pythonic.