-
Hajipur, Bihar, 844101
A stack is a linear data structure that follows the LIFO (Last In, First Out) principle — the last element added is the first one to be removed.
Python doesn’t have a built-in stack data type, but stacks can be easily implemented using lists or the collections.deque
module.
stack = []
# Push elements
stack.append(10)
stack.append(20)
stack.append(30)
print(stack) # [10, 20, 30]
# Pop element
stack.pop() # Removes 30
print(stack) # [10, 20]
Method | Description |
---|---|
append(x) |
Push item onto stack |
pop() |
Pop top item from stack |
[-1] |
Peek top item (no remove) |
len() |
Stack size |
collections.deque
(Recommended)from collections import deque
stack = deque()
stack.append("a")
stack.append("b")
stack.append("c")
print(stack.pop()) # Output: c
✅ deque
is faster and more memory-efficient for stack operations than lists.
To check the top without removing it:
top = stack[-1]
print("Top element:", top)
if not stack:
print("Stack is empty")
else:
print("Stack is not empty")
Undo operations in editors
Backtracking in games
Expression evaluation
Function call stack
Q1. Write a Python program to create an empty stack and add three items to it.
Q2. Write a Python program to remove the last added item using pop()
.
Q3. Write a Python program to check the top item in the stack without removing it.
Q4. Write a Python program to print all items in a stack using a loop.
Q5. Write a Python program to use collections.deque
to push and pop names.
Q6. Write a Python program to count the number of items in a stack using len()
.
Q7. Write a Python program to create a stack and remove all items one by one using a loop.
Q8. Write a Python program to use a stack to reverse a string.
Q9. Write a Python program to check if the stack is empty and print a message accordingly.
Q10. Write a Python program to push and pop elements in numeric order and display the stack content at each step.
Q1: What principle does a stack follow?
Q2: Which method is used to push an item onto a stack (list)?
Q3: What does pop() do in a stack?
Q4: Which module provides deque in Python?
Q5: What will happen if you call pop() on an empty stack?
Q6: What is stack[-1] used for?
Q7: Which structure uses LIFO?
Q8: What is the main limitation of using lists for stacks?
Q9: Which stack method is not available in Python lists?
Q10: Which is better for stack operations in Python?