Welcome to our exploration of queues and deques. These structures frequently surface in everyday programming, managing everything from system processes to printer queues. In this lesson, our goal is to understand and implement queues and deques in Python. Let's dive in!
A queue, similar to waiting in line at a store, operates on the "First In, First Out" or FIFO principle. Python's built-in queue
module enables the implementation of queues. This module includes the Queue
class, with the put(item)
method for adding items and the get()
method for removing items.
Python1from queue import Queue 2 3# Create a queue and add items 4q = Queue() 5q.put("Apple") 6q.put("Banana") 7q.put("Cherry") 8 9# Remove an item 10print(q.get()) # Expects "Apple"
The dequeued item, "Apple"
, was the first item we inserted, demonstrating the FIFO principle of queues.
Before trying to remove items from our queue, let's ensure they are not empty. This precaution will prevent runtime errors when attempting to dequeue from an empty queue.
Python1from queue import Queue 2 3# Create a queue and enqueue items 4q = Queue() 5q.put("Item 1") 6q.put("Item 2") 7 8# Check if the queue is non-empty, then dequeue an item 9if not q.empty(): 10 print(q.get()) # Expects "Item 1"
A deque, or "double-ended queue", allows the addition and removal of items from both ends. Python provides the collections
module containing the deque
class for implementing deques. We can add items to both ends of our deque using the append(item)
method for the right end and the appendleft(item)
method for the left.
Python1from collections import deque 2 3# Create a deque and add items 4d = deque() 5d.append("Middle") 6d.append("Right end") 7d.appendleft("Left end") 8 9# Remove an item 10print(d.pop()) # Expects "Right end" 11 12# Remove an item from the left 13print(d.popleft()) # Expects "Left end"
The deque
class offers a feature not found in regular queues: item rotation. Using the rotate()
method, we can shift all items by a provided number.
Python1from collections import deque 2 3# Create a deque 4d = deque(["Apple", "Banana", "Cherry"]) 5 6# Rotate the deque 7d.rotate(1) # Rotates to the right by one place 8 9print(d) # Expects deque(['Cherry', 'Apple', 'Banana'])
Here, rotate(1)
shifts all items to the right.
Congratulations on finishing this detailed study of queues and deques in Python! You've learned their operating principles and how to construct and manipulate them in Python.
Prospectively, we aim to comprehend additional data structures like these. This quest opens up a world of opportunities for expressing your ideas and solving complex problems. Are you ready for forthcoming practice exercises to consolidate this new knowledge? Let's continue our exploration!