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 theappend()
method, and inQueue
, useput()
. - To remove elements from the queue: in
deque
, use thepopleft()
method, and inQueue
, useget()
. - 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()
Page of .
Leave a comment
You must be logged in to leave a comment.
Log in or
sign up to join the discussion.
Comments (0)