sta

Learn Stacks and Queues in Python

Python Snippets for Learning Stacks and Queues

Stacks

# Creating a Stack
stack = []
# Pushing elements
stack.append(3); stack.append(7); stack.append(5)
# Popping elements
stack.pop()
# Checking if stack is empty
is_empty = not stack
# Getting the top element without popping
top_element = stack[-1] if stack else None
# Size of the stack
size = len(stack)
# Clearing the stack
stack.clear()

Queues

from collections import deque
# Creating a Queue
queue = deque()
# Enqueueing elements
queue.append(3); queue.append(7); queue.append(5)
# Dequeueing an element
if queue:
queue.popleft()
# Checking if queue is empty
is_empty = not queue
# Getting the front element without dequeueing
front_element = queue[0] if queue else None
# Size of the queue
size = len(queue)

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top