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.

Answer from Cecil Curry on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › queue-in-python
Queue in Python - GeeksforGeeks
May 29, 2026 - Initial queue: deque(['a', 'b', 'c']) Elements dequeued from the queue: a b c Queue after removing elements: deque([]) Explanation: popleft() efficiently removes the first element without shifting, making deque ideal for queues. Python’s queue module provides a thread-safe FIFO queue.
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
🌐
W3Schools
w3schools.com › python › python_dsa_queues.asp
Queues with Python
Size: Finds the number of elements in the queue. Queues can be implemented by using arrays or linked lists.
🌐
Educative
educative.io › answers › how-to-implement-a-queue-in-python
How to implement a queue in Python
The following methods we have used to implement queue: append(): It inserts the specified element into the queue. popleft(): It removes and returns the element at the front of the queue.
🌐
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 - This is analogous to a physical ... and provide efficient insertion and deletion. They can be implemented using arrays, linked lists, stacks, or dequeues....
🌐
Runestone Academy
runestone.academy › ns › books › published › pythonds › BasicDS › ImplementingaQueueinPython.html
4.12. Implementing a Queue in Python — Problem Solving with Algorithms and Data Structures
It is again appropriate to create a new class for the implementation of the abstract data type queue. As before, we will use the power and simplicity of the list collection to build the internal representation of the queue.
🌐
Analytics Vidhya
analyticsvidhya.com › home › queue in python: an in-depth guide
Queue in Python: An In-Depth Guide
August 12, 2024 - IsFull: Checking if the queue is full (if implemented with a fixed size). Time complexity: O(1) – Constant time operation. Size: Returns the number of elements in the queue.
🌐
Python
docs.python.org › 3 › library › queue.html
queue — A synchronized queue class
Put item into the queue. The method never blocks and always succeeds (except for potential low-level errors such as failure to allocate memory). The optional args block and timeout are ignored and only provided for compatibility with Queue.put(). CPython implementation detail: This method has a C implementation which is reentrant.
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-is-queue-implemented-in-python
Queue Implementation in Python - GeeksforGeeks
July 23, 2025 - The simplest way to implement a queue in Python is by using a built-in list.
🌐
PythonForBeginners
pythonforbeginners.com › home › implement queue in python
Implement Queue in Python - PythonForBeginners.com
July 16, 2021 - To implement a queue with linked list in python, we will first define a node object which will have the current element and will point to the node which will be inserted just after it.
🌐
Techie Delight
techiedelight.com › home › queue › queue implementation in python
Queue Implementation in Python | Techie Delight
September 12, 2025 - enqueue: Inserts an element at the rear (right side) of the queue. dequeue: Removes the element from the front (left side) of the queue and returns it. peek: Returns the element at the front of the queue without removing it. ... The time complexity of all the above operations should be constant. ... The queue can easily be implemented as a list...
🌐
Wondershare EdrawMax
edrawmax.wondershare.com › home › for it service › implementing a queue in python: step-by-step tutorial
Implementing Queues in Python: A Comprehensive Guide
Queues are a fundamental data structure ... breadth-first search algorithms, and more. In Python, queues can be implemented easily using built-in data structures like lists or collections dequeue....
🌐
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
🌐
Upgrad
upgrad.com › home › tutorials › software & tech › queue in python
Queue in Python – Learn Different Ways to Implement Queues
May 28, 2025 - When using a Python list as a queue in Python, these methods come in handy: append(item): Adds an element to the end of the list (enqueue). pop(0): Removes the first element of the list (dequeue).
🌐
SSOJet
ssojet.com › data-structures › implement-queue-in-python
Implement Queue in Python | Implement Data Structures in Programming Languages
Implement a queue in Python efficiently using `collections.deque`. Learn practical applications and code examples for managing FIFO data structures.
🌐
CodingNomads
codingnomads.com › python-301-build-python-queue
How to Build a Python Queue
This implementation of a Queue class has five methods: .__init__(): Initializes an empty queue with None values for the head and tail attributes.
🌐
STEMpedia
ai.thestempedia.com › home › examples › python queue implementation
Python Queue Implementation - Example Project
August 11, 2023 - Initialize an empty myQueue list. Use the enqueue function to add elements (person’s codes) to the queue.