Python Stack Data Structure Tutorial
Implement a LIFO stack in Python. Run our interactive stack code example to master push, pop, peek, and capacity limits.
How it Works
A Stack is a linear data structure that follows the Last-In, First-Out (LIFO) principle. This means that the last element added to the stack is the very first one to be removed, similar to a stack of plates.
The stack supports two main operations: push (adds an item to the top) and pop (removes the most recently added item). Additionally, a peek or top operation allows inspecting the top element without removing it.
In Python, stacks can be easily built using a list with `.append()` and `.pop()` methods, or by using the `collections.deque` object which offers optimized double-ended queue operations in O(1) time.
Source Code
A custom Stack implementation using Python's list structure to emulate push, pop, and peek functions.
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return len(self.items) == 0
def push(self, item):
self.items.append(item)
print(f"Pushed: {item}")
def pop(self):
if self.is_empty():
return "Underflow: Stack is empty"
popped = self.items.pop()
print(f"Popped: {popped}")
return popped
def peek(self):
if self.is_empty():
return "Stack is empty"
return self.items[-1]
def size(self):
return len(self.items)
# Initialize stack
stack = Stack()
stack.push("Apples")
stack.push("Bananas")
stack.push("Cherries")
print(f"Current Stack Size: {stack.size()}")
print(f"Top Element (Peek): {stack.peek()}")
stack.pop()
print(f"Stack after Pop: {stack.items}")Pushed: Apples
Pushed: Bananas
Pushed: Cherries
Current Stack Size: 3
Top Element (Peek): Cherries
Popped: Cherries
Stack after Pop: ['Apples', 'Bananas']Real-world Applications
- Managing undo functions in software systems
- Syntax parsing and parentheses checking in compilers
- Tracking execution call stacks during recursion in engines
Frequently Asked Questions
Why is collections.deque preferred over a normal list for Stacks?
While lists are convenient, they are dynamic arrays under the hood. When they resize, memory reallocation can take O(n) time. The deque object uses a doubly linked list architecture, guaranteeing O(1) pushes and pops.
Can stacks overflow in Python?
A standard stack class in Python using list arrays will grow until it consumes all available system memory. The recursion stack in Python, however, has a default limit (typically 1000) to prevent infinite loops from crashing the interpreter.