Cover Image for Python Stack & Queue
226 views

Python Stack & Queue

The Python, you can implement a stack and a queue using various data structures and libraries. Here’s how to implement both a stack and a queue:

Stack:

A stack is a linear data structure that follows the Last-In, First-Out (LIFO) principle, meaning that the last element added is the first one to be removed.

  1. Using Lists: You can implement a stack using Python lists by using the append() method to push elements onto the stack and the pop() method to remove elements from the top of the stack:
   stack = []

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

   # Pop elements from the stack
   popped_element = stack.pop()
   print("Popped Element:", popped_element)
  1. Using collections.deque: The collections module provides a deque (double-ended queue) data structure, which can be used to implement a stack with efficient push and pop operations:
   from collections import deque

   stack = deque()

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

   # Pop elements from the stack
   popped_element = stack.pop()
   print("Popped Element:", popped_element)

Queue:

A queue is a linear data structure that follows the First-In, First-Out (FIFO) principle, meaning that the first element added is the first one to be removed.

  1. Using Lists: You can implement a simple queue using Python lists by using the append() method to enqueue elements and the pop(0) method to dequeue elements:
   queue = []

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

   # Dequeue elements
   dequeued_element = queue.pop(0)
   print("Dequeued Element:", dequeued_element)
  1. Using collections.deque: The collections module also provides a deque that can be used to implement a queue. It offers efficient enqueue and dequeue operations:
   from collections import deque

   queue = deque()

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

   # Dequeue elements
   dequeued_element = queue.popleft()
   print("Dequeued Element:", dequeued_element)
  1. Using queue.Queue: The queue module provides the Queue class, which is a thread-safe queue implementation. It can be used for implementing a simple queue:
   import queue

   q = queue.Queue()

   # Enqueue elements
   q.put(1)
   q.put(2)
   q.put(3)

   # Dequeue elements
   dequeued_element = q.get()
   print("Dequeued Element:", dequeued_element)

Choose the implementation that best suits your needs based on your specific use case and requirements. If you need thread-safe queues, consider using the queue.Queue class. For basic stack and queue operations, using lists or collections.deque should suffice.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS