SimpleTuts.com

Stack and Queue in Python

Stack

A stack is a collection of elements that follows the Last In, First Out (LIFO) principle. This means that the last element added to the stack will be the first one to be removed.

Operations

Example using a list


stack = []

# Push elements
stack.append(1)
stack.append(2)
stack.append(3)

print("Stack after pushing:", stack)

# Pop elements
print("Popped element:", stack.pop())
print("Stack after popping:", stack)

# Peek/Top element
print("Top element:", stack[-1])

# Check if stack is empty
print("Is stack empty?", len(stack) == 0)
Python Online Compiler

Output

Stack after pushing: [1, 2, 3]
Popped element: 3
Stack after popping: [1, 2]
Top element: 2
Is stack empty? False

Queue

A queue is a collection of elements that follows the First In, First Out (FIFO) principle. This means that the first element added to the queue will be the first one to be removed.

Operations

Example using collections.deque


from collections import deque

queue = deque()

# Enqueue elements
queue.append(1)
queue.append(2)
queue.append(3)

print("Queue after enqueuing:", queue)

# Dequeue elements
print("Dequeued element:", queue.popleft())
print("Queue after dequeuing:", queue)

# Front element
print("Front element:", queue[0])

# Check if queue is empty
print("Is queue empty?", len(queue) == 0)
Python Online Compiler

Output

Queue after enqueuing: deque([1, 2, 3])
Dequeued element: 1
Queue after dequeuing: deque([2, 3])
Front element: 2
Is queue empty? False