I'd avoid declaring an instance of a class inside the definition of a class. Declaring self.head = Queue(data) is asking for trouble, in my mind, because that could lead to declarations of self.head.head, and self.head.head.head... You get the idea. Instead, I would maybe separate things out a bit. Also, notice that you didn't declare self.head.next or self.head.item, even though you called them in your methods.

Perhaps declare two classes, one for Nodes, and the other for a Queue built out of Nodes? That would simplify things a bit.

Here's how I would build a Queue in Python, credit my own:

from typing import Iterable

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

    def __call__(self):
        return self.data

class Queue:
    def __init__(self, x=None):
        assert isinstance(x, Node) or (x == None) or isinstance(x, Iterable)
        if isinstance(x, Iterable):
            self.head = Node(x[0])
            self.tail = Node(x[0])
            self.length = 1
            self.to_queue(x[1:])
        else:
            self.head = x
            self.tail = x
            self.length = 1 if x else 0

    def enqueue(self, data):
        tmp = self.head
        self.head = Node(data)
        self.head.next = tmp
        self.length += 1

    def dequeue(self):
        if self.length <= 0:
            print("empty Queue")
            return
        tmp = self.head
        for i in range(self.length-2):
            tmp = tmp.next
        self.tail = tmp
        self.tail.next = None
        self.length -= 1
        if self.length == 0:
            self.head = None
            self.tail = None

    def to_queue(self, vals):
        for i in vals:
            self.enqueue(i)

    def __call__(self):
        tmp = self.head
        while (tmp):
            print(tmp.data, end=" ")
            tmp = tmp.next

    def __len__(self):
        return self.length

Note that this is all unnecessary for production code, as you could just use a deque, for example, from the collections module

Answer from bug_spray on Stack Overflow
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ queue.html
queue โ€” A synchronized queue class
February 23, 2026 - It is especially useful in threaded programming when information must be exchanged safely between multiple threads. The Queue class in this module implements all the required locking semantics.
๐ŸŒ
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
This allows us to use the insert function on lists to add new elements to the rear of the queue. The pop operation can be used to remove the front element (the last element of the list). Recall that this also means that enqueue will be O(n) and dequeue will be O(1). ... class Queue: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def enqueue(self, item): self.items.insert(0,item) def dequeue(self): return self.items.pop() def size(self): return len(self.items)
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ queue-in-python
Queue in Python - GeeksforGeeks
December 11, 2025 - Explanation: queue.Queue class handles thread-safe operations.
๐ŸŒ
w3resource
w3resource.com โ€บ python-exercises โ€บ oop โ€บ python-oop-exercise-10.php
Python OOP: Queue class with enqueue and dequeue methods
July 9, 2025 - In the example usage section, we create an instance of the Queue class called queue. We enqueue several items into the queue using the "enqueue()" method. In addition, we demonstrate how to dequeue an item from the queue using the dequeue method. ... Write a Python class for a Queue that supports enqueue and dequeue operations using collections.deque for optimal performance.
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_dsa_queues.asp
Queues with Python
To better understand the benefits with using arrays or linked lists to implement queues, you should check out this page that explains how arrays and linked lists are stored in memory. This is how a queue can be implemented using a linked list. ... class Node: def __init__(self, data): self.data = data self.next = None class Queue: def __init__(self): self.front = None self.rear = None self.length = 0 def enqueue(self, element): new_node = Node(element) if self.rear is None: self.front = self.rear = new_node self.length += 1 return self.rear.next = new_node self.rear = new_node self.length += 1
Top answer
1 of 3
2

I'd avoid declaring an instance of a class inside the definition of a class. Declaring self.head = Queue(data) is asking for trouble, in my mind, because that could lead to declarations of self.head.head, and self.head.head.head... You get the idea. Instead, I would maybe separate things out a bit. Also, notice that you didn't declare self.head.next or self.head.item, even though you called them in your methods.

Perhaps declare two classes, one for Nodes, and the other for a Queue built out of Nodes? That would simplify things a bit.

Here's how I would build a Queue in Python, credit my own:

from typing import Iterable

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

    def __call__(self):
        return self.data

class Queue:
    def __init__(self, x=None):
        assert isinstance(x, Node) or (x == None) or isinstance(x, Iterable)
        if isinstance(x, Iterable):
            self.head = Node(x[0])
            self.tail = Node(x[0])
            self.length = 1
            self.to_queue(x[1:])
        else:
            self.head = x
            self.tail = x
            self.length = 1 if x else 0

    def enqueue(self, data):
        tmp = self.head
        self.head = Node(data)
        self.head.next = tmp
        self.length += 1

    def dequeue(self):
        if self.length <= 0:
            print("empty Queue")
            return
        tmp = self.head
        for i in range(self.length-2):
            tmp = tmp.next
        self.tail = tmp
        self.tail.next = None
        self.length -= 1
        if self.length == 0:
            self.head = None
            self.tail = None

    def to_queue(self, vals):
        for i in vals:
            self.enqueue(i)

    def __call__(self):
        tmp = self.head
        while (tmp):
            print(tmp.data, end=" ")
            tmp = tmp.next

    def __len__(self):
        return self.length

Note that this is all unnecessary for production code, as you could just use a deque, for example, from the collections module

2 of 3
0

Another approach could be to implement the queue as two stacks:

class Stack():
    def __init__(self):
        self.items = []
    def push(self, item):
        self.items.append(item)
    def pop(self):
        if len(self.items) == 0:
            raise IndexError("Can't pop from an empty stack!")
        return self.items.pop(len(self.items) - 1)
    def isEmpty(self):
        return len(self.items) == 0

class Queue():
    def __init__(self):
        self.stack1 = Stack()
        self.stack2 = Stack()
    def enqueue(self, item):
        self.stack1.push(item)
    def dequeue(self):
        if self.stack2.isEmpty():
            while not self.stack1.isEmpty():
                self.stack2.push(self.stack1.pop())
        return self.stack2.pop()
    def isEmpty(self):
        return self.stack1.isEmpty() and self.stack2.isEmpty()

But I agree with the other answers that for any serious project, the standard library and its collections module should be preferred.

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
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ home โ€บ python_data_structure โ€บ python queue data structure
Python Data Structure - Queue
February 13, 2026 - A queue can be implemented using python list where we can use the insert() and pop() methods to add and remove elements. Their is no insertion as data elements are always added at the end of the queue.
Find elsewhere
๐ŸŒ
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
๐ŸŒ
Medium
medium.com โ€บ analytics-vidhya โ€บ queues-in-python-7783244ac507
Using Queues in Python. Helps new Python programmers know howโ€ฆ | by Jekayin-Oluwa Olabemiwo | Analytics Vidhya | Medium
February 23, 2021 - Therefore, we shall import the deque() datatype which is inbuilt in Python. ... Then, let us declare our Queue class. from collections import deque โ€‹ #new addition class Queue: def __init__(self): self.items = deque() We have declared the Queue class and added the __init__() constructor which enables us to be able to use objects of the Queue class.
๐ŸŒ
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 provides a simple queue implementation to enqueue and dequeue elements in Python. ... The Queue class provided by the queue module can be used for safely exchanging objects between multiple threads or processes.
๐ŸŒ
W3Schools
w3schools.com โ€บ dsa โ€บ dsa_data_queues.php
DSA Queues
No shifting: The front element of the queue can be removed (dequeue) without having to shift other elements in the memory. Reasons for not using linked lists to implement queues: Extra memory: Each queue element must contain the address to the next element (the next linked list node). Readability: The code might be harder to read and write for some because it is longer and more complex. This is how a queue can be implemented using a linked list. ... class Node: def __init__(self, data): self.data = data self.next = None class Queue: def __init__(self): self.front = None self.rear = None self.l
๐ŸŒ
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.
๐ŸŒ
Spark By {Examples}
sparkbyexamples.com โ€บ home โ€บ python โ€บ queue in python with examples
Queue in Python with Examples - Spark By {Examples}
May 31, 2024 - There are two common ways to implement ... Letโ€™s see them one by one. In Python, a queue can be implemented using a class with methods for enqueue, dequeue, size, and isEmpty....
๐ŸŒ
Real Python
realpython.com โ€บ queue-in-python
Python Stacks, Queues, and Priority Queues in Practice โ€“ Real Python
December 1, 2023 - You can quickly verify this in an interactive Python session: ... >>> from queues import Stack >>> lifo = Stack("1st", "2nd", "3rd") >>> for element in lifo: ... print(element) ... 3rd 2nd 1st ยท With an identical setup and test data as before, the elements return to you in reverse order, which is the expected behavior of a LIFO queue. Note: In this tutorial, you use inheritance as a convenient mechanism to reuse code. However, the current class ...
๐ŸŒ
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 - For many real-world queues, there is a limit to how many items can be enqueued before the queue is considered full. We can add a maxsize parameter to check capacity when enqueueing: class Queue: def __init__(self, maxsize=10): self.items = [] self.maxsize = maxsize # Rest of methods...
๐ŸŒ
Geekflare
geekflare.com โ€บ home โ€บ development โ€บ understanding queue implementation in python
Understanding Queue implementation in Python
June 1, 2021 - Python has a built-in module called queue that serves a class called Queue for the queue implementation.
๐ŸŒ
Built In
builtin.com โ€บ data-science โ€บ priority-queues-in-python
Introduction to Priority Queues in Python | Built In
Yes, a priority queue can be implemented in Python by using a list, importing the heapq module or importing the queue module and using the PriorityQueue class. For the heapq module and PriorityQueue class, each comes with functions (for heapq) ...
๐ŸŒ
iO Flood
ioflood.com โ€บ blog โ€บ python-queue
Python Queue Class | Usage Guide (With Examples)
February 5, 2024 - In the above example, we first import the queue module and create a queue instance q. We then use the put method to add items to the queue. The get method is used to remove and return the first item from the queue. The empty method checks if the queue is empty and returns a boolean value. This basic usage of Pythonโ€™s queue module is straightforward and intuitive.
๐ŸŒ
Educative
educative.io โ€บ answers โ€บ how-to-implement-a-queue-in-python
How to implement a queue in Python
A queue follows the FIFO principle ... (LIFO) data structure. In Python, it can be implemented using a list or the collections.deque class....