Post thumbnail
PYTHON

Mastering Stacks and Queues with Python

By Basil Ahamed

What’s the secret behind web browsers remembering your navigation history or how printers manage multiple jobs in an orderly fashion? The answer lies in stacks and queues—two foundational data structures that quietly power some of the most efficient algorithms and real-world systems. These deceptively simple tools are the backbone of many programming challenges, from reversing strings to managing recursive calls.

In this blog, we’re diving into the mechanics of stacks and queues, their practical uses, and how you can bring them to life with Python. No matter, if you’re taking your first steps in programming or looking to enhance your expertise, mastering these structures, will give you the edge needed to solve increasingly complex problems.

Table of contents


  1. What Are Stacks and Queues?
    • Stacks
    • Queues
  2. Why Learn Stacks and Queues?
  3. Implementing Stacks and Queues in Python
    • Implementing a Stack
    • Implementing a Queue
  4. Tips for Mastery
  5. Conclusion

What Are Stacks and Queues?

Stacks

A stack is a linear data structure that follows the Last In, First Out (LIFO) principle. This means the last item added to the stack is the first one to be removed. Think of it as a stack of plates in a cafeteria: you add plates to the top, and the last plate placed is the first one taken.

Key Operations:

  • Push: Add an item to the stack.
  • Pop: Remove the top item from the stack.
  • Peek: Retrieve the top item without removing it.
  • IsEmpty: Check if the stack is empty.

Queues

A queue is a linear data structure that adheres to the First In, First Out (FIFO) principle. Imagine a queue at a ticket counter: the first person in line is the first to be served.

Key Operations:

  • Enqueue: Add an item to the rear of the queue.
  • Dequeue: Remove the front item from the queue.
  • Peek: Retrieve the front item without removing it.
  • IsEmpty: Check if the queue is empty.

Why Learn Stacks and Queues?

  • Efficient Memory Use: They are lightweight and use memory efficiently.
  • Algorithm Foundations: They are integral to solving problems in recursion, breadth-first search, depth-first search, and more.
  • Real-World Applications: Used in undo functionality, job scheduling, printer tasks, and call stack management.

Implementing Stacks and Queues in Python

1. Implementing a Stack

Python’s list data structure provides built-in methods that align with stack operations. Alternatively, we can use the collections.deque for optimized performance.

Using list:

class Stack:

    def __init__(self):

        self.stack = []

    def push(self, item):

        self.stack.append(item)

    def pop(self):

        if not self.is_empty():

            return self.stack.pop()

        return “Stack is empty”

    def peek(self):

        if not self.is_empty():

            return self.stack[-1]

        return “Stack is empty”

    def is_empty(self):

        return len(self.stack) == 0

    def size(self):

        return len(self.stack)

Example:

s = Stack()

s.push(10)

s.push(20)

print(s.pop())  # Output: 20

print(s.peek())  # Output: 10

2. Implementing a Queue

Queue Implementation Using List

Using a list, we can add elements to the end (enqueue) and access or inspect elements at the front (peek) without removing them. Although this approach is not the most efficient for large-scale operations, it is simple and effective for learning and smaller use cases.

class Queue:

    def __init__(self):

        self.queue = []

    def enqueue(self, element):

        self.queue.append(element)

        print(f”{element} added to queue”)

    def dequeue(self):

        if not self.is_empty():

            removed_element = self.queue.pop(0)

            print(f”{removed_element} removed from queue”)

            return removed_element

        else:

            print(“Queue is empty. Cannot dequeue.”)

            return None

    def is_empty(self):

        return len(self.queue) == 0

    def display(self):

        print(“Queue contents:”, self.queue)

Example:

queue = Queue()

queue.enqueue(1)

queue.enqueue(2)

queue.dequeue()

queue.display()

  • Using collections.deque:

The deque from ’s collections module is a double-ended queue that allows fast appending and popping from both ends.

from collections import deque

class Queue:

    def __init__(self):

        self.queue = deque()

    def enqueue(self, item):

        self.queue.append(item)

    def dequeue(self):

        if not self.is_empty():

            return self.queue.popleft()

        return “Queue is empty”

    def peek(self):

        if not self.is_empty():

            return self.queue[0]

        return “Queue is empty”

    def is_empty(self):

        return len(self.queue) == 0

    def size(self):

        return len(self.queue)

Example Usage:

q = Queue()

q.enqueue(1)

q.enqueue(2)

print(q.dequeue())  # Output: 1

print(q.peek())     # Output: 2

Also Read: Linked List in Data Structure: A Complete Guide

MDN

Tips for Mastery

  1. Practice Real-World Problems: Implement stacks and queues in real-life scenarios, such as web browser backtracking or task scheduling.
  2. Understand Limitations: While ’s list works for stack operations, it may not be as efficient as deque for large-scale operations.
  3. Combine Data Structures: Use stacks and queues with other structures, like graphs or trees, to solve complex problems.
  4. Dive Into Libraries: Explore ’s collections and queue modules to leverage built-in functionality.

Ready to take your tech career to the next level with Python? GUVI’s Python Course is perfect for all skill levels, offering an in-depth curriculum, hands-on projects, and expert mentorship. Gain the knowledge and skills needed to succeed in exciting fields like AI, Data Science, and Web Development. Start your path to career transformation with Python today!

Conclusion

Stacks and queues may seem straightforward, but their versatility makes them indispensable for solving both everyday programming challenges and high-stakes computational problems. From managing data flows to optimizing memory use, these structures shine in their simplicity and effectiveness.

Now that you’ve explored their inner workings and Python implementations, it’s time to think bigger: How can these tools streamline your next coding project? Keep experimenting, solving, and connecting these concepts to larger applications—you’ll soon find yourself appreciating their brilliance in new and unexpected ways.

Career transition

Did you enjoy this article?

Schedule 1:1 free counselling

Similar Articles

Loading...
Share logo Copy link
Power Packed Webinars
Free Webinar Icon
Power Packed Webinars
Subscribe now for FREE! 🔔
close
Webinar ad
Table of contents Table of contents
Table of contents Articles
Close button

  1. What Are Stacks and Queues?
    • Stacks
    • Queues
  2. Why Learn Stacks and Queues?
  3. Implementing Stacks and Queues in Python
    • Implementing a Stack
    • Implementing a Queue
  4. Tips for Mastery
  5. Conclusion