Stack & Queue in Python¶
--8<: "core-logic/stack-queue.md"
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.