Lesson Overview

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!

Introduction to Queues

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.

from queue import Queue

# Create a queue and add items
q = Queue()
q.put("Apple")
q.put("Banana")
q.put("Cherry")

# Remove an item
print(q.get())  # Expects "Apple"

The dequeued item, "Apple", was the first item we inserted, demonstrating the FIFO principle of queues.

Practical Implementation 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.

from queue import Queue

# Create a queue and enqueue items
q = Queue()
q.put("Item 1")
q.put("Item 2")

# Check if the queue is non-empty, then dequeue an item
if not q.empty():
    print(q.get())  # Expects "Item 1"
Introduction to Deques

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.

from collections import deque

# Create a deque and add items
d = deque()
d.append("Middle")
d.append("Right end")
d.appendleft("Left end")

# Remove an item
print(d.pop())  # Expects "Right end"

# Remove an item from the left
print(d.popleft()) # Expects "Left end"
Practical Implementation of Deques

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.

from collections import deque

# Create a deque
d = deque(["Apple", "Banana", "Cherry"])

# Rotate the deque
d.rotate(1)  # Rotates to the right by one place

print(d)  # Expects deque(['Cherry', 'Apple', 'Banana'])

Here, rotate(1) shifts all items to the right.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal