Introduction To Stack
Introduction To Stack
A stack is a linear data structure that follows the Last In First Out (LIFO) principle. This means the last
element pushed onto the stack will be the first one to be removed. Stacks primarily support two operations:
- Push : Adds an element to the top of the stack.
- Pop : Removes the element from the top of the stack.
In Python, lists can be used to implement stacks, where `append()` acts as the push operation, and `pop()`
acts as the pop operation.
1
# Popping elements from the stack
element1 = stack.pop() # Pop the top element (30)
print("Popped element:", element1)
Now let’s make the code more reusable by implementing push and pop operations using functions.
2
#### Combined Example (with functions)
popped_element2 = pop(stack)
print("Popped element:", popped_element2)
1. Question : Write a Python function that pushes 5 elements onto a stack and then pops 2 elements. Print
the stack after each operation.
- Answer :
def pop(stack):
if len(stack) == 0:
print("Stack is empty!")
return None
return stack.pop()
3
# Push 5 elements
push(stack, 10)
push(stack, 20)
push(stack, 30)
push(stack, 40)
push(stack, 50)
# Pop 2 elements
pop(stack)
print("Stack after popping:", stack)
pop(stack)
print("Stack after popping:", stack)
2. Question : Create a Python program that checks if a stack is empty before performing a pop operation. If
the stack is empty, it should print a message indicating so.
- Answer :
def pop(stack):
if len(stack) == 0:
print("Stack is empty, cannot pop!")
return None
return stack.pop()
3. Question : How can you implement a peek operation in Python that returns the top element of the stack
without removing it?
- Answer :
def peek(stack):
if len(stack) == 0:
print("Stack is empty, nothing to peek!")
return None
return stack[-1]