Stack Operations
3
8
5
TOP
Size: 3
Push, pop, and peek on a stack - see LIFO behavior animate in real time.
Time O(1) · Space O(n)
class Stack:
def __init__(self):
"""Initialize an empty stack."""
self.items = []
def push(self, item):
"""Add an item to the top of the stack."""
self.items.append(item)
def pop(self):
"""
Remove and return the top item from the stack.
Raises IndexError if stack is empty.
"""
if self.is_empty():
raise IndexError("Cannot pop from empty stack")
return self.items.pop()
def peek(self):
"""
Return the top item without removing it.
Raises IndexError if stack is empty.
"""
if self.is_empty():
raise IndexError("Cannot peek empty stack")
return self.items[-1]
def is_empty(self):
"""Return True if the stack is empty."""
return len(self.items) == 0
def size(self):
"""Return the number of items in the stack."""
return len(self.items)
def __len__(self):
"""Allow len(stack) syntax."""
return self.size()
def __str__(self):
"""String representation: bottom -> top."""
return f"Stack({self.items})"
# Example usage:
if __name__ == "__main__":
stack = Stack()
# Push elements
stack.push(10)
stack.push(20)
stack.push(30)
print(stack) # Stack([10, 20, 30])
# Peek at top
print(stack.peek()) # 30
# Pop elements
print(stack.pop()) # 30
print(stack.pop()) # 20
print(stack) # Stack([10])
A stack is a linear data structure that follows the Last-In, First-Out (LIFO) principle. The last element added is the first one removed. Stacks are fundamental in computer science, appearing in function call management, expression evaluation, and undo mechanisms.
Push adds an element to the top of the stack. Pop removes and returns the top element. Peek returns the top element without removing it. All operations run in constant time.