📚 12.10 Dive into Stack: Data Structure & Python Implementation

Imagine a stack of books – you add new books on top and remove from the top. This everyday concept is exactly what the Stack data structure does in programming. In this blog, we will explore what a stack is, its operations like push and pop, and how to implement it using Python lists.


🔹 What is a Stack?

A Stack is a linear data structure that follows the LIFO principle – Last In, First Out. This means the last element added to the stack is the first one to be removed.

It’s like stacking plates: you place a plate on top (push), and when you need one, you remove the top plate (pop).


⚙️ Basic Operations on Stack

1. Push

Adds (inserts) an element to the top of the stack.

2. Pop

Removes and returns the top element from the stack.

3. Peek (Optional)

Returns the top element without removing it (also known as top()).

4. isEmpty

Checks whether the stack is empty.


🛠️ Implementing Stack using List in Python

Python’s built-in list type can be used to implement a stack. We use append() for push and pop() for pop operations.

✅ Example Code:

stack = []

# Push elements
stack.append(10)
stack.append(20)
stack.append(30)

print("Current Stack:", stack)

# Pop element
popped = stack.pop()
print("Popped Element:", popped)
print("Stack after pop:", stack)

💡 Output:

Current Stack: [10, 20, 30]
Popped Element: 30
Stack after pop: [10, 20]

🧪 Complete Stack Implementation with Functions

def push(stack, item):
    stack.append(item)

def pop(stack):
    if not stack:
        return "Stack Underflow!"
    return stack.pop()

def display(stack):
    print("Current Stack:", stack)

# Testing
my_stack = []
push(my_stack, 5)
push(my_stack, 10)
push(my_stack, 15)
display(my_stack)

print("Popped:", pop(my_stack))
display(my_stack)

🧾 Summary Table: Stack Operations

Operation Description Python List Method
Push Add element to top of stack append()
Pop Remove element from top of stack pop()
isEmpty Check if stack is empty len(stack) == 0

📝 Summary

  • A Stack follows the LIFO principle – Last In, First Out.
  • Push adds and pop removes elements from the top of the stack.
  • Python’s list provides simple methods like append() and pop() for stack implementation.

💡 Tip: Stacks are used in undo features, function call tracking, and syntax parsing!

Start stacking your knowledge with Python – one block at a time! 🚀📚

Previous Post Next Post