In Python, a Stack is a data structure that follows the LIFO(Last In First Out) technique to store data. Stack provides two operations to implement it.
push method:- to add an element to the top of the stack.
pop method:- to remove an element from the top of the stack.
Stack class with methods for pushing, popping, checking if the stack is empty, getting the size of the stack, and peeking at the top element.
# Declaring Custom Stack Class class Stack: # constructor automatically invoked once, stack instance created. # it will items array which is associated with class instance def __init__(self): self.items = [] # push function to add item in the end of stack. def push(self, item): self.items.append(item) def size(self): return len(self.items) # pop function to remove last item from stack. def pop(self): if not self.is_empty(): return self.items.pop() else: print("Stack is empty") return None def is_empty(self): return len(self.items) == 0 def peek(self): if not self.is_empty(): return self.items[-1] else: print("Stack is empty") return None # stack instance created s = Stack()
Add items within the stack by calling the `push()` function of Stack Class.
# adding items within stack by calling push function of Stack Class. s.push(1) s.push(2) s.push(3) # Print the size of stack print("Size of the stack:", s.size()) # Output: 3
# print peek value in stack else peek function will return None Data Type value print("Stack Peek Value: ", s.peek()) # Output: 3
Checking Peek value in Stack else return None Data Type value
# pop function to remove last item from stack. def pop(self): if not self.is_empty(): return self.items.pop() else: print("Stack is empty") return None
If no element exist in stack then it will return "Stack is empty" message
print("Popping elements:") # Remove last element from stack print(s.pop()) # Output: 3 # Remove last element from stack print(s.pop()) # Output: 2 # Remove last element from stack print(s.pop()) # Output: 1 # Remove last element from stack print(s.pop()) # Output: Stack is empty, None
Create an empty stack: stack = "Stack()".
Check if the stack is empty: "stack.is_empty()".
Push an item onto the stack: "stack.push(item)".
Get the size of the stack: "stack.size()".
Check the Peek value in the stack without removing items: "stack.peek()".
Pop the top item from the stack: "stack.pop()".