Introduction to Stacks

What is a Stack?

Stack is an abstract data type that represents a collection of elements with a last-in, first-out (LIFO) behavior. It can be visualized as a stack of objects where new elements are added to the top and removed from the top.

In a stack, the element that is added most recently is the first one to be removed, which follows the Last-In-First-Out principle. This behavior is often referred to as "push" for adding elements and "pop" for removing elements from the stack.

The main operations associated with a stack are:

Push: This operation adds an element to the top of the stack.

Pop: This operation removes and returns the topmost element from the stack.

Peek/Top: This operation returns the topmost element without removing it from the stack.

Stacks are commonly used in various algorithms and applications, such as expression evaluation, function call management, backtracking, and undo functionality.


A real-life example of a stack can be seen in the behavior of a stack of plates in a restaurant or kitchen.

Imagine a stack of plates on a counter. When new plates arrive, they are placed on top of the stack, and when plates are needed, they are taken from the top of the stack. This operation follows the Last-In-First-Out (LIFO) principle, which is the fundamental behavior of a stack.

Stack Operations(Push, Pop, Top/Peek)

Here's an example of implementing a stack using a list (array) in Python:

class Stack:

    def __init__(self):

        self.stack = []


    def is_empty(self):

        return len(self.stack) == 0


    def push(self, element):

        self.stack.append(element)


    def pop(self):

        if not self.is_empty():

            return self.stack.pop()

        else:

            raise Exception("Stack is empty")


    def peek(self):

        if not self.is_empty():

            return self.stack[-1]

        else:

            raise Exception("Stack is empty")


In this example, the Stack class represents a stack and provides methods to perform stack operations:

is_empty(): Checks if the stack is empty.

push(element): Adds an element to the top of the stack.

pop(): Removes and returns the topmost element from the stack.

peek(): Returns the topmost element without removing it from the stack.

You can create an instance of the Stack class and perform stack operations on it:


Here's an example usage of the Stack:

my_stack = Stack()


my_stack.push(10)

my_stack.push(20)

my_stack.push(30)


print(my_stack.pop())  # Output: 30

print(my_stack.peek())  # Output: 20

print(my_stack.is_empty())  # Output: False