Python Stacks


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 Using List

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]

🔸 Key List Methods
Method Description
append(x) Push item onto stack
pop() Pop top item from stack
[-1] Peek top item (no remove)
len() Stack size

🔹 Stack Using 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.


🔹 Peeking Top Item

To check the top without removing it:

top = stack[-1]
print("Top element:", top)

🔹 Checking If Stack is Empty

if not stack:
    print("Stack is empty")
else:
    print("Stack is not empty")

🔹 Use Case Examples

  • Undo operations in editors

  • Backtracking in games

  • Expression evaluation

  • Function call stack


Practice Questions

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.


Go Back Top