Python: Stack Implementation with Lists

1. Introduction

A stack is a data structure that follows the Last-In-First-Out (LIFO) principle. This means that the most recently added element is the first one to be removed. Stacks are very useful in scenarios like function calls, algorithms like depth-first search, and much more. In this blog post, we'll learn how to implement a basic stack using Python's built-in list structure.

2. Program Overview

We will implement the following basic stack operations:

1. Push: Adds an item to the top of the stack.

2. Pop: Removes and returns the top item from the stack.

3. Peek: Returns the top item from the stack without removing it.

4. is_empty: Checks if the stack is empty.

5. size: Returns the number of elements in the stack.

3. Code Program

class Stack:
    def __init__(self):
        """Initialize an empty stack."""
        self.items = []

    def push(self, item):
        """Add an item to the top of the stack."""

    def pop(self):
        """Remove and return the top item from the stack."""
        if not self.is_empty():
            return self.items.pop()
        return None

    def peek(self):
        """Return the top item from the stack without removing it."""
        if not self.is_empty():
            return self.items[-1]
        return None

    def is_empty(self):
        """Check if the stack is empty."""
        return len(self.items) == 0

    def size(self):
        """Return the number of items in the stack."""
        return len(self.items)

# Demonstration of the Stack operations
s = Stack()
print(f"Top of the stack: {s.peek()}")
print(f"Stack size: {s.size()}")
print(f"Pop from the stack: {s.pop()}")
print(f"Stack after pop operation: {s.size()}")


Top of the stack: 2
Stack size: 2
Pop from the stack: 2
Stack after pop operation: 1

4. Step By Step Explanation

The Stack class provides a basic implementation of a stack using a Python list. The list is dynamically resizable, allowing push and pop operations to be executed in constant time. The push method adds an item to the top, the pop method removes the top item, and the peek method lets us view the top item without removal. The is_empty and size methods offer utility functions to check the status of the stack. The demonstration shows these methods in action.