PYTHON

Implementing Basic Stacks and Queues with Python Lists

Learn to implement fundamental Last-In, First-Out (LIFO) stacks and First-In, First-Out (FIFO) queues using Python's built-in list data structure.

# --- Stack (LIFO - Last In, First Out) ---
stack = []

# Push elements
stack.append('Task 1')
stack.append('Task 2')
stack.append('Task 3')
print(f"Stack after push: {stack}") # ['Task 1', 'Task 2', 'Task 3']

# Pop elements
popped_item = stack.pop()
print(f"Popped from stack: {popped_item}") # Task 3
print(f"Stack after pop: {stack}") # ['Task 1', 'Task 2']

# --- Queue (FIFO - First In, First Out) ---
queue = []

# Enqueue elements
queue.append('User A')
queue.append('User B')
queue.append('User C')
print(f"Queue after enqueue: {queue}") # ['User A', 'User B', 'User C']

# Dequeue elements (using pop(0) for FIFO)
dequed_item = queue.pop(0)
print(f"Dequeued from queue: {dequed_item}") # User A
print(f"Queue after dequeue: {queue}") # ['User B', 'User C']

# Note: For efficient queues with many operations, collections.deque is preferred.
How it works: Python's list can serve as a simple stack (LIFO) using `append()` for pushing and `pop()` for popping elements from the end. For a basic queue (FIFO), `append()` adds elements to the end, and `pop(0)` removes elements from the beginning. While `pop(0)` on a list is inefficient for very large queues (due to element shifting), this pattern is useful for small-scale scenarios or conceptual understanding in web development contexts like task processing.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs