🌐
Python
docs.python.org › 3 › library › queue.html
queue — A synchronized queue class
Source code: Lib/queue.py The queue module implements multi-producer, multi-consumer queues. It is especially useful in threaded programming when information must be exchanged safely between multip...
🌐
GeeksforGeeks
geeksforgeeks.org › python › queue-in-python
Queue in Python - GeeksforGeeks
May 29, 2026 - Queue is a linear data structure that stores items in a First In First Out (FIFO) manner. The item that is added first will be removed first.
🌐
W3Schools
w3schools.com › python › python_dsa_queues.asp
Queues with Python
Python Examples Python Compiler ... Q&A Python Bootcamp Python Training ... A queue is a linear data structure that follows the First-In-First-Out (FIFO) principle....
🌐
CodeSignal
codesignal.com › learn › courses › advanced-built-in-data-structures-and-their-usage › lessons › understanding-queues-and-deques-in-python
Understanding Queues and Deques in Python
A queue, similar to waiting in line at a store, operates on the "First In, First Out" or FIFO principle. Python's built-in queue module enables the implementation of queues.
🌐
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 - Queues are a useful data structure in programming that allow you to add and remove elements in a first in, first out (FIFO) order. Python provides a built-in module called queue that implements different types of queue data structures.
🌐
Medium
medium.com › @shras_a › queue-in-python-34a74641502e
Queue in Python. Queues are fundamental data structures… | by Shravya | Medium
November 14, 2024 - Queue in Python Queues are fundamental data structures that follows the First In, First Out (FIFO) principle, meaning the first element added to the queue will be the first one to be removed. Think …
🌐
Real Python
realpython.com › ref › stdlib › queue
queue | Python Standard Library – Real Python
The Python queue module provides reliable thread-safe implementations of the queue data structure.
🌐
Readthedocs
pydoc-zh.readthedocs.io › en › latest › library › queue.html
8.10. Queue — A synchronized queue class — Python 2.7.6 documentation
The module implements three types of queue, which differ only in the order in which the entries are retrieved. In a FIFO queue, the first tasks added are the first retrieved. In a LIFO queue, the most recently added entry is the first retrieved (operating like a stack).
Find elsewhere
🌐
YouTube
youtube.com › watch
Queues in Python Explained [ Step-by-Step Guide to Data Structures & Algorithms ] - YouTube
👉 Join my Python Masterclass ~ https://www.zerotoknowing.com/join-now👉 Join our Discord Community ~ https://discord.gg/dvrcpXSwyc📚 Read my eBooks ~ https:...
Published   July 17, 2025
🌐
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 ...
It operates much like real-world queues or lines, where the first element inserted is the first one to be removed. For example, consider a line of people waiting to buy tickets at a theater. The person who arrives first gets their ticket first. In computer science, a Queue works in exactly the same way. In Python, we can implement Queues using built-in data types.
🌐
GitHub
github.com › python › cpython › blob › main › Lib › queue.py
cpython/Lib/queue.py at main · python/cpython
'''Simple, unbounded FIFO queue. · This pure Python implementation is not reentrant. ''' # Note: while this pure Python version provides fairness · # (by using a threading.Semaphore which is itself fair, being based · # on threading.Condition), fairness is not part of the API contract.
Author   python
🌐
Server Academy
serveracademy.com › blog › stop-using-lists-for-queues-a-python-queue-deep-dive
Stop Using Lists for Queues: A Python Queue Deep Dive Blog | Server Academy
May 3, 2026 - Discover how to use Python queues efficiently. We compare lists, collections.deque, and the queue module for FIFO, LIFO, and thread safe data structures.
🌐
W3Schools
w3schools.com › python › ref_module_queue.asp
Python queue Module
Python Examples Python Compiler ... Q&A Python Bootcamp Python Training ... The queue module provides synchronized queue classes for multi-producer, multi-consumer scenarios....
Top answer
1 of 1
1

Firstly, for Python you need to be really aware what the benefits of multithreading/multiprocessing gives you. IMO you should be considering multiprocessing instead of multithreading. Threading in Python is not actually concurrent due to GIL and there are many explanations out on which one to use. Easiest way to choose is to see if your program is IO-bound or CPU-bound. Anyways on to the Queue which is a simple way to work with multiple processes in python.

Using your pseudocode as an example, here is how you would use a Queue.

import multiprocessing



def main_1(output_queue):
    test = 0
    while test <=10: # simple limit to not run forever
        data = [1,2,3]
        print("Process 1: Sending data")
        output_queue.put(data) #Puts data in queue FIFO
        test+=1
    output_queue.put("EXIT") # triggers the exit clause

def main_2(input_queue,output_queue):
    file = 0 # Dummy psuedo variables
    limit = 1
    while True:
        rec_data = input_queue.get() # Get the latest data from queue. Blocking if empty
        if rec_data == "EXIT": # Exit clause is a way to cleanly shut down your processes
            output_queue.put("EXIT")
            print("Process 2: exiting")
            break
        print("Process 2: saving to file:", rec_data, "count = ", file)
        file += 1
        #save_to_file(rec_data)
        if file>limit:
            file = 0 
            output_queue.put(True)

def main_3(input_queue):
    while(True):
        signal = input_queue.get()

        if signal is True:
            print("Process 3: Data sent and removed")
            #send_data_to_external_device()
            #remove_data_from_disk()
        elif signal == "EXIT":
            print("Process 3: Exiting")
            break

if __name__== '__main__':

    q1 = multiprocessing.Queue() # Intializing the queues and the processes
    q2 = multiprocessing.Queue()
    p1 = multiprocessing.Process(target = main_1,args = (q1,))
    p2 = multiprocessing.Process(target = main_2,args = (q1,q2,))
    p3 = multiprocessing.Process(target = main_3,args = (q2,))

    p = [p1,p2,p3]
    for i in p: # Start all processes
        i.start()
    for i in p: # Ensure all processes are finished
        i.join()

The prints may be a little off because I did not bother to lock the std_out. But using a queue ensures that stuff moves from one process to another.

EDIT: DO be aware that you should also have a look at multiprocessing locks to ensure that your file is 'thread-safe' when performing the move/delete. The pseudo code above only demonstrates how to use queue

🌐
Read the Docs
stackless.readthedocs.io › en › 2.7-slp › library › queue.html
8.10. Queue — A synchronized queue class — Stackless-Python 2.7.15 documentation
The module implements three types of queue, which differ only in the order in which the entries are retrieved. In a FIFO queue, the first tasks added are the first retrieved. In a LIFO queue, the most recently added entry is the first retrieved (operating like a stack).
🌐
Code Without Rules
codewithoutrules.com › 2017 › 08 › 16 › concurrency-python
The tragic tale of the deadlocking Python queue
August 16, 2017 - This is a story about how very difficult it is to build concurrent programs. It’s also a story about a bug in Python’s Queue class, a class which happens to be the easiest way to make concurrency simple in Python. This is not a happy story: this is a tragedy, a story of deadlocks and despair.
Top answer
1 of 1
1

It's unclear what you mean by "Queue". The only two standard Queue implementations I'm aware of cannot be iterated over, so "casting it as a list" just raises an exception:

>>> import queue
>>> q = queue.Queue()
>>> list(q)
Traceback (most recent call last):
    ...
TypeError: 'Queue' object is not iterable

>>> from multiprocessing import Queue
>>> q = Queue()
>>> list(q)
Traceback (most recent call last):
    ...
TypeError: 'Queue' object is not ierable

Whether you may ever need to do:

with lock_object:
    some_function(queue)

can't be answered based on what you've said so far. If, for example, your higher-level logic relies on putting the queue into (in effect) "read only" mode for some time, then, sure. You'll need a lock to ensure mutual exclusion between the reading and writing sides for the duration.

.put() and .get() on their own are already thread- and process- (in the case of multiprocessing.Queue) safe.

More than just that is not guaranteed by the docs, so can't be relied on even if it "appears to" work (which, if so, may be a reliable accident of the specific Python implementation you're using, or may be a fickle accident due to your simply not having yet bumped into a relevant race condition).

NEW QUESTION, NEW ANSWER

The question was edited to ask about list(queue.queue) instead. That falls under the earlier "accident of the specific Python implementation you're using", in two respects:

  1. It's not documented that a Queue.queue object has a queue attribute. Python is a "consenting adults" language, and doesn't try to prevent you from using implementation details. But, if you do, you're on your own. The implementation may change at any time.
  2. It so happens that list(deque) is thread-safe today (CPython 3.12.5), but that's not documented either. I only know that it is because I stared at the C implementation code. It may not be thread-safe in 3.12.6. More generally, CPython is moving toward a "no GIL" mode of operation, in which this kind of thing becomes much more likely to suffer races.

The bottom line doesn't change: .put() and .get() on their own are already thread- and process- (in the case of multiprocessing.Queue) safe. Nothing more than that is guaranteed. Really! ;-) Nothing. If you need more than just that much to be reliable across implementations and releases, you'll need to supply your own locks.

🌐
Python
docs.python.org › 3 › library › asyncio-queue.html
Queues — Python 3.14.6 documentation
Source code: Lib/asyncio/queues.py asyncio queues are designed to be similar to classes of the queue module. Although asyncio queues are not thread-safe, they are designed to be used specifically i...
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
Top answer
1 of 2
78

For your second example, you already gave the explanation yourself---Queue is a module, which cannot be called.

For the third example: I assume that you use Queue.Queue together with multiprocessing. A Queue.Queue will not be shared between processes. If the Queue.Queue is declared before the processes then each process will receive a copy of it which is then independent of every other process. Items placed in the Queue.Queue by the parent before starting the children will be available to each child. Items placed in the Queue.Queue by the parent after starting the child will only be available to the parent. Queue.Queue is made for data interchange between different threads inside the same process (using the threading module). The multiprocessing queues are for data interchange between different Python processes. While the API looks similar (it's designed to be that way), the underlying mechanisms are fundamentally different.

  • multiprocessing queues exchange data by pickling (serializing) objects and sending them through pipes.
  • Queue.Queue uses a data structure that is shared between threads and locks/mutexes for correct behaviour.
2 of 2
12

Queue.Queue

  • Was created to work in concurrent environments spawned with the threading module.

  • Each thread shares a reference to the Queue.Queue object among them. No copying or serialization of data happens here and all the threads have access to the same data inside the queue.

multiprocessing.Queue

  • Was created to work in parallel environments spawned with the multiprocessing module.

  • Each process gets access to a copy of the multiprocessing.Queue object among them. The contents of the queue are copied across the processes via pickle serialization. .