How to implement a queue in Python

Queues are a data structure used to store collections of elements in a first-in, first-out (FIFO) order. Just like in a real-life queue — whoever enters first leaves first.

In Python, queues can be implemented using the deque() class from the collections module or the queue module.

  • To add elements to the queue: in deque, use the append() method, and in Queue, use put().
  • To remove elements from the queue: in deque, use the popleft() method, and in Queue, use get().
  • To check the size of the queue, use len().

It’s important to note that queue.Queue is designed for multithreaded programming.

from collections import deque  # or
from queue import Queue

# Creating a queue using deque
myqueue = deque()

# Creating a queue using Queue
myqueue = Queue()

Comments (0)

Leave a comment