A stack in Python is a linear data structure that adheres to the Last-In, First-Out
(LIFO) principle. This means that the last element added to the stack is the first one
to be removed. Imagine a stack of plates: we add new plates to the top, and when
we take a plate, we take it from the top, which is the last one you put there.
Key Operations of a Stack:
Push: Adds an element to the top of the stack.
Pop: Removes and returns the top element from the stack.
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.
Implementing a Stack in Python:
Python lists are commonly used to implement stacks due to
their built-in append() and pop() methods, which directly
correspond to the push and pop operations of a stack.
stack = []
[Link]('a') # Push
[Link]('b')
[Link]('c')
print("Initial stack:", stack)
print("Popped elements:")
print([Link]()) # Pop
print([Link]())
print([Link]())
print("Stack after popping:", stack)
output
Initial stack: ['a', 'b', 'c']
Popped elements:
c
b
a
Stack after popping: []
Using [Link]
from collections import deque
# Create a deque
dq = deque([1, 2, 3])
# Append elements
[Link](4) # Add to the right
[Link](5)
[Link](0) # Add to the left
# Pop elements
[Link]() # Remove from the right
[Link]() # Remove from the left
print(dq) # Output: deque([1, 2, 3])
# Stack implementation using a list
stack = []
# Push operation
[Link](10)
[Link](20)
[Link](30)
# Pop operation
print("Popped element:", [Link]())
# Peek operation
if stack:
print("Top element:", stack[-1])
# Check if stack is empty
print("Is stack empty?", len(stack) == 0)