Stack & Queue in Python
Stack & Queue in Python is a core Python concept covering stack & Queue in Python: --8<: "core-logic/stack-queue.md" This topic is essential for academic learning, board exam preparation, and developing optimized real-world code.
Stacks and Queues
These are linear data structures that control how data is added and removed.
1. Stack (LIFO)
- Logic: "Last-In, First-Out".
- Analogy: A stack of plates. You add a plate to the top, and you take the top plate off first.
- Operations:
Push: Add item to top.Pop: Remove item from top.
2. Queue (FIFO)
- Logic: "First-In, First-Out".
- Analogy: A line of people waiting for a bus. The person who arrived first is served first.
- Operations:
Enqueue: Add item to the end.Dequeue: Remove item from the front.
Applications
- Stacks are used for "Undo" features and Function Calls (The Call Stack).
- Queues are used for printer tasks and handling web requests.
1. Stack Implementation
In Python, you can easily use a List as a stack using append() and pop().
stack = []
# Push
stack.append("A")
stack.append("B")
# Pop
print(stack.pop()) # "B"
print(stack.pop()) # "A"
2. Queue Implementation
For a queue, using a standard list is inefficient (because deleting the first item requires shifting all other items). Instead, use collections.deque.
from collections import deque
queue = deque()
# Enqueue
queue.append("First")
queue.append("Second")
# Dequeue
print(queue.popleft()) # "First"
print(queue.popleft()) # "Second"
Summary Comparison
| Data Structure | Logic | Python Recommended Tool |
|---|---|---|
| Stack | LIFO | list (append/pop) |
| Queue | FIFO | collections.deque (append/popleft) |
Performance
collections.deque is optimized for fast appends and pops from both ends.