🌐
Python
docs.python.org › 3 › library › queue.html
queue — A synchronized queue class
Raises ShutDown if the queue has been shut down and is empty, or if the queue has been shut down immediately. ... Equivalent to get(False). Two methods are offered to support tracking whether enqueued tasks have been fully processed by daemon consumer threads.
🌐
GeeksforGeeks
geeksforgeeks.org › python › queue-in-python
Queue in Python - GeeksforGeeks
May 29, 2026 - There are various ways to implement a queue in Python by following ways: Lists can be used as queues, but removing elements from front requires shifting all other elements, making it O(n).
Discussions

Implementing an efficient queue in Python - Stack Overflow
As Uri Goren astutely noted above, the Python stdlib already implemented an efficient queue on your fortunate behalf: collections.deque. Avoid reinventing the wheel by hand-rolling your own: Linked list implementation. While doing so reduces the worst-case time complexity of your dequeue() and enqueue() methods ... More on stackoverflow.com
🌐 stackoverflow.com
Peek method in Priority Queue?
The heapq object is a list. So you can peek with standard indexing. I don't think there's a way to peek on a queue.Queue, just due to how they are implemented. More on reddit.com
🌐 r/learnpython
2
1
September 26, 2020
uninterrupted methods in threads

If you want to use a class as a thread, write it as a subclass of threading.Thread. And why do you supply x to the class if it's going to use the queue anyway?

from threading import Thread

class DoSomethingOnSecondThread(Thread):
def __init__(self, q):
self.queue = q
def run(self):
while True:
# Grab list of who is connected to wifi
Event.wait(60)
self.queue.put(True)

Then, don't use a blocking call to queue.get, because that will make the main loop a slave to DoSomethingOnSecondThread as you mentioned. The docs on the queue library also mention this, and they even have a shortcut to a non-blocking get:

Queue.get(block=True, timeout=None)Remove and return an item from the queue. If optional args block is true and timeout is None (the default), block if necessary until an item is available. If timeout is a positive number, it blocks at most timeout seconds and raises the Empty exception if no item was available within that time. Otherwise (block is false), return an item if one is immediately available, else raise the Empty exception (timeout is ignored in that case).

Queue.get_nowait()Equivalent to get(False).

Also don't use the library name queue as the name for one specific queue, as it then poses a conflict if you want to use any other functionality, like the queue.Empty exception.

    second_thread_q = Queue()
ts = DoSomethingonSecondThread(second_thread_q)
ts.start()
x = False
while True:
print(x)
try:
x = second_thread_q.get_nowait()
except queue.Empty:
pass
# do something else
More on reddit.com
🌐 r/learnpython
2
8
February 20, 2017
[Question] Removing objects from a list while iterating over it
Try to iterate over a copy of the original list: for i in lst[:]: if i == 2: lst.remove(i) You can also do that without a for loop, with list comprehension: new_lst = [i for i in lst if i != 2] Note that solution may be faster, and is considered cleaner. More on reddit.com
🌐 r/Python
26
4
November 8, 2010
🌐
W3Schools
w3schools.com › python › python_dsa_queues.asp
Queues with Python
Python Overview Python Built-in Functions Python String Methods Python List Methods Python Dictionary Methods Python Tuple Methods Python Set Methods Python File Methods Python Keywords Python Exceptions Python Glossary · Built-in Modules Random Module Requests Module Statistics Module Math Module cMath Module · Remove List Duplicates Reverse a String Add Two Numbers · Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Training ... A queue is a linear data structure that follows the First-In-First-Out (FIFO) principle.
🌐
Medium
basillica.medium.com › working-with-queues-in-python-a-complete-guide-aa112d310542
Working with Queues in Python — A Complete Guide | by Basillica | Medium
March 27, 2024 - You can initialize a Queue instance like this: from queue import Queue q = Queue() # The key methods available are: qsize() # - Get the size of the queue empty() # - Check if queue is empty full() # - Check if queue is full put(item) # - Put ...
🌐
Educative
educative.io › answers › how-to-implement-a-queue-in-python
How to implement a queue in Python
Queues in Python can be implemented using lists (with append() and pop(0)), the Queue module (using methods like put(), get(), and empty()), or the collections.deque module (using append() and popleft() for efficient operations).
🌐
Great Learning
mygreatlearning.com › blog › it/software development › python queue
Python Queue
October 14, 2024 - The built-in methods in Python are the insert() and pop() functions that are used to add and remove elements from the queue. Lists are a little slow as compared with queues and the reason behind this is when we insert a new element to the list, ...
🌐
TutorialsPoint
tutorialspoint.com › python_data_structure › python_queue.htm
Python Data Structure - Queue
In the below example we create a queue class where we insert the data and then remove the data using the in-built pop method. class Queue: def __init__(self): self.queue = list() def addtoq(self,dataval): # Insert method to add element if dataval not in self.queue: self.queue.insert(0,dataval) return True return False # Pop method to remove element def removefromq(self): if len(self.queue) > 0: return self.queue.pop() return ("No elements in Queue!") TheQueue = Queue() TheQueue.addtoq("Mon") TheQueue.addtoq("Tue") TheQueue.addtoq("Wed") print(TheQueue.removefromq()) print(TheQueue.removefromq())b
🌐
Medium
medium.com › @shras_a › queue-in-python-34a74641502e
Queue in Python. Queues are fundamental data structures… | by Shravya | Medium
November 14, 2024 - Let’s explore each of these methods, along with examples. A simple way to create a queue is by using a Python list and utilizing the append() and pop(0) methods.
Find elsewhere
🌐
Llego
llego.dev › home › blog › implementing a queue in python: a step-by-step guide
Implementing a Queue in Python: A Step-by-Step Guide - llego.dev
August 5, 2023 - In Python, queues can be implemented using lists or the collections.deque object. We will focus on building one from scratch with lists. We will create a Queue class containing the key methods enqueue and dequeue.
🌐
Real Python
realpython.com › queue-in-python
Python Stacks, Queues, and Priority Queues in Practice – Real Python
December 1, 2023 - It’s a basic priority queue implementation, which defines a heap of elements using a Python list and two methods that manipulate it. The .enqueue_with_priority() method takes two arguments, a priority and a corresponding value, which it then wraps in a tuple and pushes onto the heap using the heapq module.
Top answer
1 of 8
41

As Uri Goren astutely noted above, the Python stdlib already implemented an efficient queue on your fortunate behalf: collections.deque.

What Not to Do

Avoid reinventing the wheel by hand-rolling your own:

  • Linked list implementation. While doing so reduces the worst-case time complexity of your dequeue() and enqueue() methods to O(1), the collections.deque type already does so. It's also thread-safe and presumably more space and time efficient, given its C-based heritage.
  • Python list implementation. As I note below, implementing the enqueue() methods in terms of a Python list increases its worst-case time complexity to O(n). Since removing the last item from a C-based array and hence Python list is a constant-time operation, implementing the dequeue() method in terms of a Python list retains the same worst-case time complexity of O(1). But who cares? enqueue() remains pitifully slow.

To quote the official deque documentation:

Though list objects support similar operations, they are optimized for fast fixed-length operations and incur O(n) memory movement costs for pop(0) and insert(0, v) operations which change both the size and position of the underlying data representation.

More critically, deque also provides out-of-the-box support for a maximum length via the maxlen parameter passed at initialization time, obviating the need for manual attempts to limit the queue size (which inevitably breaks thread safety due to race conditions implicit in if conditionals).

What to Do

Instead, implement your Queue class in terms of the standard collections.deque type as follows:

from collections import deque

class Queue:
    '''
    Thread-safe, memory-efficient, maximally-sized queue supporting queueing and
    dequeueing in worst-case O(1) time.
    '''


    def __init__(self, max_size = 10):
        '''
        Initialize this queue to the empty queue.

        Parameters
        ----------
        max_size : int
            Maximum number of items contained in this queue. Defaults to 10.
        '''

        self._queue = deque(maxlen=max_size)


    def enqueue(self, item):
        '''
        Queues the passed item (i.e., pushes this item onto the tail of this
        queue).

        If this queue is already full, the item at the head of this queue
        is silently removed from this queue *before* the passed item is
        queued.
        '''

        self._queue.append(item)


    def dequeue(self):
        '''
        Dequeues (i.e., removes) the item at the head of this queue *and*
        returns this item.

        Raises
        ----------
        IndexError
            If this queue is empty.
        '''

        return self._queue.pop()

The proof is in the hellish pudding:

>>> queue = Queue()
>>> queue.enqueue('Maiden in Black')
>>> queue.enqueue('Maneater')
>>> queue.enqueue('Maiden Astraea')
>>> queue.enqueue('Flamelurker')
>>> print(queue.dequeue())
Flamelurker
>>> print(queue.dequeue())
Maiden Astraea
>>> print(queue.dequeue())
Maneater
>>> print(queue.dequeue())
Maiden in Black

It Is Dangerous to Go Alone

Actually, don't do that either.

You're better off just using a raw deque object rather than attempting to manually encapsulate that object in a Queue wrapper. The Queue class defined above is given only as a trivial demonstration of the general-purpose utility of the deque API.

The deque class provides significantly more features, including:

...iteration, pickling, len(d), reversed(d), copy.copy(d), copy.deepcopy(d), membership testing with the in operator, and subscript references such as d[-1].

Just use deque anywhere a single- or double-ended queue is required. That is all.

2 of 8
10

You can keep head and tail node instead of a queue list in queue class

class Node:
    def __init__(self, item = None):
        self.item = item
        self.next = None
        self.previous = None


class Queue:
    def __init__(self):
        self.length = 0
        self.head = None
        self.tail = None

    def enqueue(self, value):
        newNode = Node(value)
        if self.head is None:
            self.head = self.tail = newNode
        else:
            self.tail.next = newNode
            newNode.previous = self.tail
            self.tail = newNode
        self.length += 1

    def dequeue(self):
        item = self.head.item
        self.head = self.head.next 
        self.length -= 1
        if self.length == 0:
            self.tail = None
        return item
🌐
Real Python
realpython.com › ref › stdlib › queue
queue | Python Standard Library – Real Python
Along the way, you'll get to know the different types of queues, implement them, and then learn about the higher-level queues in Python's standard library. Be prepared to do a lot of coding. ... Get a Python Cheat Sheet (PDF) and learn the basics of Python, like working with data types, dictionaries, lists, and Python functions:
🌐
Javatpoint
javatpoint.com › queue-in-python
Queue in Python - Javatpoint
Queue in Python with python, tutorial, tkinter, button, overview, entry, checkbutton, canvas, frame, environment set-up, first python program, basics, data types, operators, etc.
🌐
CodeSignal
codesignal.com › learn › courses › linked-lists-stacks-and-queues-in-python › lessons › understanding-and-implementing-queues-exploring-core-concepts-python-implementation-and-time-complexity
Understanding and Implementing Queues: Exploring Core ...
In Python, we can implement Queues using built-in data types. Indeed, the Python list datatype comes in handy here. Python lists, however, have a significant drawback: the pop(0) method has
🌐
Scaler
scaler.com › home › topics › queue in python
Queue in Python - Scaler Topics
May 19, 2022 - Hence, the list implementation ... a queue using a list, then the append() method is used in place of the enqueue() method, and the pop() method is used in place of the dequeue() method....
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › python queue methods
Python Queue Methods - Spark By {Examples}
May 31, 2024 - Python Queue methods are used to implement the queues very efficiently. The queue is a one-dimensional data structure which is also referred to as a FIFO
🌐
Analytics Vidhya
analyticsvidhya.com › home › queue in python: an in-depth guide
Queue in Python: An In-Depth Guide
August 12, 2024 - There are several ways to implement queues in Python: Python lists can be used to implement a queue.
🌐
GeeksforGeeks
geeksforgeeks.org › python › implementation-of-queue-using-list-in-python
Implementation of Queue using List in Python - GeeksforGeeks
July 23, 2025 - Check if size == 0 (queue is empty), display “Queue is empty”. If not empty: retrieve the element at the front index and move front = (front + 1) % capacity. Also, decrement size by 1 and return the removed element. ... # python3 program for insertion and # deletion in Circular Queue class MyQueue: def __init__(self, c): self.l = [None] * c self.cap = c self.size = 0 self.front = 0 def getFront(self): # Check if queue is empty if self.size == 0: return None return self.l[self.front] def getRear(self): # Check if queue is empty if self.size == 0: return None # Calculate rear index rear = (s
🌐
Simplilearn
simplilearn.com › home › resources › software development › queue in python: working with queue data structure in python
Queue in Python: Working With Queue Data Structure in Python
March 5, 2026 - A queue is a built-in module of python used in threaded programming. It stores items sequentially in a FIFO manner. Learn all about the queue in python now!
Address   5851 Legacy Circle, 6th Floor, Plano, TX 75024 United States
🌐
Intellipaat
intellipaat.com › home › blog › python queue tutorial: queue module, deque & priority queue (2026)
Python Queue: queue.Queue, deque & PriorityQueue Explained with Examples
May 7, 2026 - Here’s the code example for implementing the enqueue() function in Python using a list as the underlying data structure: ... Code Copied! ... In the above code, the enqueue() function takes two parameters: queue, which represents the queue ...