Sunday 9 June 2024

Stacks and Queues in Python: A Beginner's Guide


 

In the world of data structures, stacks and queues are fundamental concepts that every programmer should understand. These data structures are essential for managing data in a specific order, and they find applications in various algorithms and real-world scenarios. In this blog, we will explore what stacks and queues are, how to implement them in Python, and provide some examples to demonstrate their usage.

What is a Stack?

A stack is a linear data structure that follows the Last-In-First-Out (LIFO) principle. This means that the last element added to the stack is the first one to be removed. Think of a stack of plates: you can only take the top plate off the stack, and when you add a plate, you place it on the top.

Common operations on a stack include:

  • Push: Add an item to the top of the stack.
  • Pop: Remove the item from the top of the stack.
  • Peek: Get the item from the top of the stack without removing it.
  • IsEmpty: Check if the stack is empty.
  • Size: Get the number of items in the stack.

Here’s a simple implementation of a stack in Python:

class Stack:

    def __init__(self):

        self.items = []


    def is_empty(self):

        return len(self.items) == 0


    def push(self, item):

        self.items.append(item)


    def pop(self):

        if self.is_empty():

            raise IndexError("pop from empty stack")

        return self.items.pop()


    def peek(self):

        if self.is_empty():

            raise IndexError("peek from empty stack")

        return self.items[-1]


    def size(self):

        return len(self.items)


    def __str__(self):

        return str(self.items)

Example Usage:

stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
print("Stack after pushing 1, 2, 3:", stack)

print("Popped item:", stack.pop())
print("Stack after popping:", stack)

print("Top item:", stack.peek())
print("Stack size:", stack.size())

What is a Queue?

A queue is a linear data structure that follows the First-In-First-Out (FIFO) principle. This means that the first element added to the queue is the first one to be removed. Think of a queue of people waiting in line: the person who gets in line first is the first one to be served.

Common operations on a queue include:

  • Enqueue: Add an item to the end of the queue.
  • Dequeue: Remove the item from the front of the queue.
  • IsEmpty: Check if the queue is empty.
  • Size: Get the number of items in the queue.

Here’s a simple implementation of a queue in Python:

class Queue:

    def __init__(self):

        self.items = []


    def is_empty(self):

        return len(self.items) == 0


    def enqueue(self, item):

        self.items.append(item)


    def dequeue(self):

        if self.is_empty():

            raise IndexError("dequeue from empty queue")

        return self.items.pop(0)


    def size(self):

        return len(self.items)


    def __str__(self):

        return str(self.items)

Example Usage:

queue = Queue()
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
print("Queue after enqueueing 1, 2, 3:", queue)

print("Dequeued item:", queue.dequeue())
print("Queue after dequeuing:", queue)

print("Queue size:", queue.size())

Stack Operations Example

Let’s delve into a few operations to understand how a stack works: 

# Push elements

stack.push(10)

stack.push(20)

stack.push(30)


print("Stack:", stack)  # Output: [10, 20, 30]


# Pop element

print("Popped element:", stack.pop())  # Output: 30


print("Stack after pop:", stack)  # Output: [10, 20]


# Peek element

print("Top element:", stack.peek())  # Output: 20


# Stack size

print("Stack size:", stack.size())  # Output: 2

Queue Operations Example

Similarly, let’s look at a few operations to see how a queue works:

# Enqueue elements

queue.enqueue(10)

queue.enqueue(20)

queue.enqueue(30)


print("Queue:", queue)  # Output: [10, 20, 30]


# Dequeue element

print("Dequeued element:", queue.dequeue())  # Output: 10


print("Queue after dequeue:", queue)  # Output: [20, 30]


# Queue size

print("Queue size:", queue.size())  # Output: 2

Conclusion

Stacks and queues are essential data structures that provide a way to store and manage data efficiently. By understanding and implementing these structures, you can solve various computational problems more effectively. In this blog, we explored the basic concepts of stacks and queues, implemented them in Python, and demonstrated their usage with simple examples. Whether you are a beginner or an experienced programmer, mastering these data structures is crucial for your programming toolkit.

0 Comments:

Post a Comment

Popular Posts

Categories

AI (28) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (121) C (77) C# (12) C++ (82) Course (66) Coursera (184) Cybersecurity (24) data management (11) Data Science (99) Data Strucures (7) Deep Learning (11) Django (6) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flutter (1) FPL (17) Google (19) Hadoop (3) HTML&CSS (46) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (46) Meta (18) MICHIGAN (5) microsoft (4) Pandas (3) PHP (20) Projects (29) Python (792) Python Coding Challenge (273) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (41) UX Research (1) web application (8)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses