In Python, a stack is a linear data structure that follows the Last-In-First-Out (LIFO) principle.
This
means the last element added to the stack is the �rst one to be removed. Think of it like a stack of plates:
you add plates to the top and remove them from the top.
Key Operations in a Stack:
1. Push: Add an element to the top of the stack.
2. Pop: Remove and return the top element from the stack.
3. Peek (or Top): View the top element without removing it.
4. IsEmpty: Check if the stack is empty.
5. Size: Get the number of elements in the stack.
Implementing a Stack in Python
Python does not have a built-in stack data structure, but you can easily implement one using a list or the
class (which is more e�cient for stack operations).
1. Using a List:
Python lists can be used as stacks because they support (to push) and (to remove the
top element).
python Copy
stack = []
# Push elements
[Link](10) # Stack: [10]
[Link](20) # Stack: [10, 20]
[Link](30) # Stack: [10, 20, 30]
# Pop elements
print([Link]()) # Output: 30 (Stack: [10, 20])
print([Link]()) # Output: 20 (Stack: [10])
# Peek at the top element
print(stack[-1]) # Output: 10
# Check if the stack is empty
print(len(stack) == 0) # Output: False
# Get the size of the stack
print(len(stack)) # Output: 1
2. Using :
The class from the module is optimized for fast appends and pops from both
ends, making it a better choice for implementing a stack.
python Copy
from collections import deque
stack = deque()
# Push elements
[Link](10) # Stack: [10]
[Link](20) # Stack: [10, 20]
[Link](30) # Stack: [10, 20, 30]
# Pop elements
print([Link]()) # Output: 30 (Stack: [10, 20])
print([Link]()) # Output: 20 (Stack: [10])
# Peek at the top element
print(stack[-1]) # Output: 10
# Check if the stack is empty
print(len(stack) == 0) # Output: False
# Get the size of the stack
print(len(stack)) # Output: 1
When to Use a Stack:
Stacks are useful in scenarios where you need to manage elements in a LIFO order, such as:
• Undo/Redo functionality in text editors.
• Backtracking algorithms (e.g., solving mazes or puzzles).
• Function call management in programming languages (the call stack).
• Parsing expressions (e.g., checking balanced parentheses).
Example: Balanced Parentheses Check
Here’s a practical example of using a stack to check if a string of parentheses is balanced:
python Copy
def is_balanced(expression):
stack = []
mapping = {')': '(', '}': '{', ']': '['}
for char in expression:
if char in [Link](): # Push opening brackets
[Link](char)
elif char in [Link](): # Check closing brackets
if not stack or [Link]() != mapping[char]:
return False
return not stack # Stack should be empty if balanced
# Test
print(is_balanced("({[]})")) # Output: True
print(is_balanced("({[}])")) # Output: False
Let me know if you'd like further clari�cation or more examples!