A Stack is a linear data structure that follows a particular order in which operations are performed. The order is LIFO (Last-In, First-Out). This means the last element added to the stack will be the first element to be removed.
A great real-world analogy is a stack of plates. You add a new plate to the top, and when you need a plate, you take one from the top. You don't pull a plate from the bottom of the stack!
A stack has two primary operations:
push: Adds an element to the top of the stack.pop: Removes the element from the top of the stack.It also has some common helper operations:
peek (or top): Returns the top element of the stack without removing it.isEmpty: Checks if the stack is empty.size: Returns the number of elements in the stack.In Python, you can easily implement a stack using the built-in list type. The list's append() method acts as push, and its pop() method (without an index) acts as pop.
// Initialize an empty stack my_stack = []// Push items onto the stack my_stack.append("Plate 1") my_stack.append("Plate 2") my_stack.append("Plate 3") print("Stack after pushes:", my_stack)
// Peek at the top item top_item = my_stack[-1] print("Top item is:", top_item)
// Pop an item from the stack removed_item = my_stack.pop() print("Popped item:", removed_item) print("Stack after pop:", my_stack)
For more structured code, you can wrap the stack logic in a class.
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return not self.items
def push(self, item):
self.items.append(item)
def pop(self):
if not self.is_empty():
return self.items.pop()
return "Stack is empty"
def peek(self):
if not self.is_empty():
return self.items[-1]
return "Stack is empty"
def size(self):
return len(self.items)
s = Stack()
s.push(10)
s.push(20)
print("Top item:", s.peek()) // 20
print("Popped item:", s.pop()) // 20
print("Stack size:", s.size()) // 1
Pro Tip: For heavy-duty stack and queue operations, Python's `collections.deque` is often more performant than a standard `list` because it's optimized for fast appends and pops from both ends.
3 + 4) to postfix and evaluating them.What does the acronym LIFO stand for?