🌐
W3Schools
w3schools.com › python › python_dsa_queues.asp
Queues with Python
Here's a complete implementation of a Queue class: Using a Python class as a queue: class Queue: def __init__(self): self.queue = [] def enqueue(self, element): self.queue.append(element) def dequeue(self): if self.isEmpty(): return "Queue is empty" return self.queue.pop(0) def peek(self): if self.isEmpty(): return "Queue is empty" return self.queue[0] def isEmpty(self): return len(self.queue) == 0 def size(self): return len(self.queue) # Create a queue myQueue = Queue() myQueue.enqueue('A') myQueue.enqueue('B') myQueue.enqueue('C') print("Queue: ", myQueue.queue) print("Peek: ", myQueue.peek()) print("Dequeue: ", myQueue.dequeue()) print("Queue after Dequeue: ", myQueue.queue) print("isEmpty: ", myQueue.isEmpty()) print("Size: ", myQueue.size()) Try it Yourself » ·
🌐
W3Schools
w3schools.com › python › ref_module_queue.asp
Python queue Module
Python Training ... The queue module provides synchronized queue classes for multi-producer, multi-consumer scenarios. Use it to safely pass work between threads using FIFO, LIFO, or priority ordering.
🌐
w3resource
w3resource.com › python-exercises › oop › python-oop-exercise-10.php
Python OOP: Queue class with enqueue and dequeue methods
July 9, 2025 - Explore object-oriented programming (OOP) in Python by creating a queue class. Learn how to implement methods for adding elements to the queue (enqueue) and removing elements from the queue (dequeue).
🌐
Python
docs.python.org › 3 › library › queue.html
queue — A synchronized queue class
February 23, 2026 - If maxsize is less than or equal to zero, the queue size is infinite. The lowest valued entries are retrieved first (the lowest valued entry is the one that would be returned by min(entries)). A typical pattern for entries is a tuple in the form: (priority_number, data). If the data elements are not comparable, the data can be wrapped in a class that ignores the data item and only compares the priority number:
🌐
W3Schools
w3schools.com › dsa › dsa_data_queues.php
DSA Queues
But to explicitly create a data structure for queues, with basic operations, we should create a queue class instead. This way of creating queues in Python is also more similar to how queues can be created in other programming languages like C and Java.
🌐
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)
🌐
Python W3schools
pythonw3schools.com › home › queue in python
Queue in Python - Python W3schools
March 17, 2023 - Elements with higher priority are removed before those with lower priority. This class requires elements to be comparable, and provides a put() method that takes a tuple of (priority, value) as its argument. queue.SimpleQueue: This is a simpler, more lightweight version of queue.Queue that is only available in Python 3.7 and later.
🌐
GeeksforGeeks
geeksforgeeks.org › python › queue-in-python
Queue in Python - GeeksforGeeks
December 11, 2025 - Explanation: popleft() efficiently removes the first element without shifting, making deque ideal for queues. Python’s queue module provides a thread-safe FIFO queue. You can specify a maxsize.
🌐
Software Testing Help
softwaretestinghelp.com › home › python programming for beginners – free python tutorials › python queue tutorial: how to implement and use python queue
Python Queue Tutorial: How To Implement And Use Python Queue
April 1, 2025 - In the simple queue data structure, the insertion of the element takes place at the rear and removes from the front position. It follows the FIFO criteria. ... ``` class demo_queue: def __init__(self): self.queue = list() def add_demo_eleme...
🌐
Stack Abuse
stackabuse.com › stacks-and-queues-in-python
Stacks and Queues in Python
August 28, 2023 - There are times when we'd like to ensure that only valid operations can be performed on our data. We can create classes that only expose the necessary methods for each data structure. To do so, let's create a new file called stack_queue.py and define two classes:
Find elsewhere
🌐
Python Module of the Week
pymotw.com › 2 › Queue
Queue – A thread-safe FIFO implementation - Python Module of the Week
$ python Queue_priority.py New job: Mid-level job New job: Low-level job New job: Important job Processing job: Important job Processing job: Mid-level job Processing job: Low-level job · As an example of how to use the Queue class with multiple threads, we can create a very simplistic podcasting ...
🌐
Educative
educative.io › answers › how-to-implement-a-queue-in-python
How to implement a queue in Python
Python offers multiple ways to implement queues, each suited to specific needs: lists for simplicity, the Queue module for thread-safe operations in concurrent programming, and the collections.deque module for efficient enqueue and dequeue operations.
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
🌐
Great Learning
mygreatlearning.com › blog › it/software development › python queue
Python Queue
October 14, 2024 - FIFO Queue: FIFO stands for “First In First Out” which means the element that will be inserted first is the element to come out first. While working with FIFO Queue in python, we need to call Queue() class from the queue module.
🌐
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.
🌐
Real Python
realpython.com › queue-in-python
Python Stacks, Queues, and Priority Queues in Practice – Real Python
December 1, 2023 - In this tutorial, you'll take a deep dive into the theory and practice of queues in programming. 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.
🌐
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
🌐
GeeksforGeeks
geeksforgeeks.org › python › stack-and-queues-in-python
Stack and Queues in Python - GeeksforGeeks
May 9, 2022 - Below is list implementation of queue. We use pop(0) to remove the first item from a list. ... # Python code to demonstrate Implementing # Queue using list queue = ["Amar", "Akbar", "Anthony"] queue.append("Ram") queue.append("Iqbal") print(queue) # Removes the first item print(queue.pop(0)) print(queue) # Removes the first item print(queue.pop(0)) print(queue)