Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Using List as Stack and Queues in Python
In this article, we will learn how to implement Stack and Queue data structures using Python lists. Both are fundamental data structures with different ordering principles: stacks follow LIFO (Last In First Out) while queues follow FIFO (First In First Out).
We'll cover the core operations for both structures −
- Insertion operation (Push for stacks, Enqueue for queues)
- Deletion operation (Pop for stacks, Dequeue for queues)
- Display / Traversing operation
Stack Implementation
A stack follows LIFO (Last In First Out) principle. Elements are added and removed from the same end called the "top".
Stack Operations
def is_empty(stack):
"""Check if stack is empty"""
return len(stack) == 0
def push(stack, item):
"""Add item to top of stack"""
stack.append(item)
print(f"Pushed {item}")
def pop(stack):
"""Remove and return top item"""
if is_empty(stack):
print("Stack Underflow - cannot pop from empty stack")
return None
item = stack.pop()
print(f"Popped {item}")
return item
def peek(stack):
"""Return top item without removing"""
if is_empty(stack):
return None
return stack[-1]
def display(stack):
"""Display stack elements from top to bottom"""
if is_empty(stack):
print("Stack is empty")
else:
print("Stack elements (top to bottom):")
for i in range(len(stack) - 1, -1, -1):
print(f" {stack[i]}")
# Example usage
stack = []
push(stack, 10)
push(stack, 20)
push(stack, 30)
display(stack)
print(f"Top element: {peek(stack)}")
pop(stack)
display(stack)
Pushed 10 Pushed 20 Pushed 30 Stack elements (top to bottom): 30 20 10 Top element: 30 Popped 30 Stack elements (top to bottom): 20 10
Queue Implementation
A queue follows FIFO (First In First Out) principle. Elements are added at the rear and removed from the front.
Queue Operations
def is_empty(queue):
"""Check if queue is empty"""
return len(queue) == 0
def enqueue(queue, item):
"""Add item to rear of queue"""
queue.append(item)
print(f"Enqueued {item}")
def dequeue(queue):
"""Remove and return front item"""
if is_empty(queue):
print("Queue Underflow - cannot dequeue from empty queue")
return None
item = queue.pop(0) # Remove from front
print(f"Dequeued {item}")
return item
def front(queue):
"""Return front item without removing"""
if is_empty(queue):
return None
return queue[0]
def display(queue):
"""Display queue elements from front to rear"""
if is_empty(queue):
print("Queue is empty")
else:
print("Queue elements (front to rear):")
for item in queue:
print(f" {item}")
# Example usage
queue = []
enqueue(queue, 'A')
enqueue(queue, 'B')
enqueue(queue, 'C')
display(queue)
print(f"Front element: {front(queue)}")
dequeue(queue)
display(queue)
Enqueued A Enqueued B Enqueued C Queue elements (front to rear): A B C Front element: A Dequeued A Queue elements (front to rear): B C
Comparison of Stack vs Queue
| Aspect | Stack | Queue |
|---|---|---|
| Principle | LIFO (Last In First Out) | FIFO (First In First Out) |
| Insertion | Top (using append) | Rear (using append) |
| Deletion | Top (using pop) | Front (using pop(0)) |
| Use Cases | Function calls, undo operations | Task scheduling, BFS |
Complete Example
# Demonstrate both stack and queue operations
print("=== STACK DEMO ===")
stack = []
for i in [1, 2, 3]:
push(stack, i)
while not is_empty(stack):
pop(stack)
print("\n=== QUEUE DEMO ===")
queue = []
for item in ['First', 'Second', 'Third']:
enqueue(queue, item)
while not is_empty(queue):
dequeue(queue)
=== STACK DEMO === Pushed 1 Pushed 2 Pushed 3 Popped 3 Popped 2 Popped 1 === QUEUE DEMO === Enqueued First Enqueued Second Enqueued Third Dequeued First Dequeued Second Dequeued Third
Conclusion
Python lists can efficiently implement both stacks and queues. Use stacks for LIFO operations like function calls or undo functionality. Use queues for FIFO operations like task scheduling or breadth-first traversals.
