HomePythonPython Program to Implement Stack

Python Program to Implement Stack

This Python program implements a basic stack data structure with the following operations:

  • is_empty(): Checks if the stack is empty.
  • push(item): Pushes an item onto the stack.
  • pop(): Pops (removes and returns) an item from the stack.
  • peek(): Returns the top item of the stack without removing it.
  • size(): Returns the size (number of elements) of the stack.

In computer science, a stack is a linear data structure that follows the Last-In-First-Out (LIFO) principle. It operates like a stack of items, where the last item added is the first one to be removed. Stacks are commonly used in various algorithms and applications, such as managing function calls in programming languages, parsing expressions, and more.

Problem Statement

Implement a stack data structure in Python with basic operations like push, pop, and peek (view the top element), and demonstrate how it works.

Python Program to Implement Stack

class Stack:
    def __init__(self):
        self.items = []

    def push(self, item):
        self.items.append(item)

    def pop(self):
        if not self.is_empty():
            return self.items.pop()
        else:
            return None  # Stack is empty

    def peek(self):
        if not self.is_empty():
            return self.items[-1]
        else:
            return None  # Stack is empty

    def is_empty(self):
        return len(self.items) == 0

    def size(self):
        return len(self.items)


# Example usage
if __name__ == "__main__":
    stack = Stack()
    print("Stack is empty:", stack.is_empty())  # Output: Stack is empty: True

    stack.push(5)
    stack.push(10)
    stack.push(15)

    print("Stack size:", stack.size())  # Output: Stack size: 3
    print("Top element:", stack.peek())  # Output: Top element: 15

    popped_item = stack.pop()
    print("Popped item:", popped_item)  # Output: Popped item: 15
    print("Stack size after pop:", stack.size())  # Output: Stack size after pop: 2

How It Works

  • The Stack class is defined with methods push, pop, peek, is_empty, and size to manage the stack operations.
  • The push method appends an item to the end of the list, simulating the action of pushing onto the stack.
  • The pop method removes and returns the last item in the list, simulating the action of popping from the stack.
  • The peek method returns the last item in the list without removing it, allowing you to view the top element.
  • The is_empty method checks if the stack is empty by examining the length of the list.
  • The size method returns the number of elements in the stack.
  • Example usage demonstrates creating a stack, performing operations, and printing the results.

Input/Output

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this Python program, we will create a singly linked list and remove duplicate elements from it. A linked list...
This Python program solves the Celebrity Problem by finding a person who is known by everyone but does not know...
This Python program uses a recursive approach to solve the n-Queens problem. It explores all possible combinations of queen placements...