Practical No 2 List-Based Stack Operations - Create A List-Based Stack and Perform Stack Operations
Practical No 2 List-Based Stack Operations - Create A List-Based Stack and Perform Stack Operations
2
List-Based Stack Operations: Create a list-based stack and perform
stack operations.
A stack is a linear data structure that follows the Last In, First Out (LIFO)
principle. The last element added to the stack is the first one to be removed. We
can implement a stack using a Python list, where the append() method simulates
the push operation, and the pop() method simulates the pop operation.
Here’s a Python program to implement a stack using a list and perform basic
stack operations like push, pop, peek, and is_empty:
Program:-
class Stack:
def __init__(self):
# Initialize the stack (empty list)
self.stack = []
def is_empty(self):
# Check if the stack is empty
return len(self.stack) == 0
def pop(self):
# Remove and return the top element of the stack
if self.is_empty():
return "Stack is empty. Cannot pop."
return self.stack.pop()
def peek(self):
# Return the top element without removing it
if self.is_empty():
return "Stack is empty. Cannot peek."
return self.stack[-1]
def display(self):
# Display the current elements in the stack
if self.is_empty():
print("Stack is empty.")
else:
print("Current Stack:", self.stack)
# Driver code
if __name__ == "__main__":
stack = Stack()
1. Class Stack:
○ The stack is represented by a list (self.stack).
○ The __init__() method initializes an empty stack.
2. Methods:
○ is_empty(): Checks if the stack is empty by comparing the length
of the stack to zero.
○ push(item): Adds an element to the top of the stack using
append().
○ pop(): Removes and returns the top element using pop(). If the
stack is empty, it returns an appropriate message.
○ peek(): Returns the top element without removing it. If the stack is
empty, it returns a message.
○ display(): Displays the current elements in the stack.
3. Driver Code:
○ Demonstrates various stack operations like push, pop, peek, and
checks if the stack is empty using the is_empty() method.
○ After each operation, the stack is displayed to show the changes.
Output:-
Explanation of Operations:
1. Push Operation: Each time we push an item onto the stack, it's added to
the end of the list using append().
2. Pop Operation: When we pop an item, it's removed from the end of the list
using pop().
3. Peek Operation: The peek operation returns the last item added without
removing it.
4. Empty Check: The is_empty() function checks if the stack is empty by
evaluating the length of the list.
This program simulates a stack with basic functionality using Python lists, which
are well-suited for this task because they allow efficient append and pop
operations.