Data Structures in Python - Episode 6: Stacks and Queues
Introduction
Stacks and Queues are basic linear data structures used for organizing data. They are very useful in many programming scenarios like backtracking, resource scheduling, etc.
---1. Stacks (LIFO - Last In First Out)
Using a List as a Stack
# Stack operations
stack = []
# Push elements
stack.append('A')
stack.append('B')
stack.append('C')
print("Stack after pushes:", stack)
# Pop element
element = stack.pop()
print("Popped Element:", element)
print("Stack after pop:", stack)
2. Queues (FIFO - First In First Out)
Using deque from collections
from collections import deque
# Queue operations
queue = deque()
# Enqueue elements
queue.append('X')
queue.append('Y')
queue.append('Z')
print("Queue after enqueues:", queue)
# Dequeue element
element = queue.popleft()
print("Dequeued Element:", element)
print("Queue after dequeue:", queue)
Quick Recap
Structure | Insertion | Removal | Python Tool |
---|---|---|---|
Stack | append() | pop() | List |
Queue | append() | popleft() | deque |
Important Notes
Tip: Use
Warning: Using list.pop(0) for queue behavior is inefficient (O(n) time).
deque
from the collections
module for fast queue operations.Warning: Using list.pop(0) for queue behavior is inefficient (O(n) time).
Comments
Post a Comment