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
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
🌐
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
🌐
Medium
medium.com › @avgengineerx01 › queue-in-python-using-a-list-6f7d7f7af3cd
Queue in Python using a List. We can implement a queue in Python… | by AvgEngineer | Medium
September 10, 2023 - #Declaring our queues in the form of a list q = [] #Inserting the elements into our queue using the append function q.append(1) #[1] q.append(2) #[1, 2] q.append(3) #[1, 2, 3] q.append(4) #[1, 2, 3, 4] #elements got inserted from the back side print(q) #Result:- [1, 2, 3, 4] #Now when we want to take out an element from queue it should from front q.pop(0) # here 0 means 0th index # 1 will be popped out as it was at 0th index and the first element print(q) #[2, 3, 4] #next front element is 2 so it will get popped out q.pop(0) print(q) #[3, 4]
🌐
W3Schools
w3schools.com › python › python_dsa_queues.asp
Queues with Python
Since Python lists has good support for functionality needed to implement queues, we start with creating a queue and do queue operations with just a few lines:
🌐
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
We need to decide which end of the list to use as the rear and which to use as the front. The implementation shown in Listing 1 assumes that the rear is at position 0 in the list. This allows us to use the insert function on lists to add new elements to the rear of the queue.
🌐
Sanfoundry
sanfoundry.com › python-program-implement-queue
Queue Program in Python - Sanfoundry
May 30, 2022 - ... The program creates a queue and allows the user to perform enqueue and dequeue operations on it. ... 1. Create a class Queue with instance variable items initialized to an empty list. 2. Define methods enqueue, dequeue and is_empty inside ...
🌐
Techie Delight
techiedelight.com › home › queue › queue implementation in python
Queue Implementation in Python | Techie Delight
September 12, 2025 - The queue can easily be implemented as a list. Following is the custom queue implementation in Python, which uses a list:
🌐
Sanfoundry
sanfoundry.com › python-program-implement-queue-data-structure-using-linked-list
Python Program to Implement Queue using Linked List - Sanfoundry
May 30, 2022 - ... 1. Create a class Node with instance variables data and next. 2. Create a class Queue with instance variables head and last. 3. The variable head points to the first element in the linked list while last points to the last element.
🌐
w3resource
w3resource.com › python-exercises › oop › python-oop-exercise-10.php
Python OOP: Queue class with enqueue and dequeue methods
July 9, 2025 - Write a Python program to create a class representing a queue data structure. Include methods for enqueueing and dequeueing elements. ... # Define a class called Queue to implement a queue data structure class Queue: # Initialize the queue with ...
Find elsewhere
🌐
Pskji
pskji.org › 75144 › write-a-python-program-to-implement-the-concept-of-queue-using-list
Write a Python Program to implement the concept of Queue using list - Pskji.org
June 28, 2022 - We need to decide which end of the list to use as the rear and which to use as the front. The implementation shown in Listing 1 assumes that the rear is at position 0 in the list.
🌐
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 - They can be implemented using arrays, linked lists, stacks, or dequeues. ... - Queues provide first-in, first-out behavior that is very useful in programming for certain situations.
🌐
GeeksforGeeks
geeksforgeeks.org › queue-in-python
Queue in Python - GeeksforGeeks
July 9, 2024 - Queue in Python can be implemented using deque class from the collections module. Deque is preferred over list in the cases where we need quicker append and pop operations from both the ends of container, as deque provides an O(1) time complexity ...
🌐
TutorialsPoint
tutorialspoint.com › program-to-implement-queue-in-python
Program to Implement Queue in Python
April 15, 2021 - ').split() operation = my_input[0].strip().lower() if operation == 'Enqueue': my_instance.enqueue_elem(int(my_input[1])) elif operation == 'Dequeue': if my_instance.check_empty(): print('The queue is empty...') else: print('The deleted value is : ', my_instance.dequeue_elem()) elif operation == 'Quit': break
🌐
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.
🌐
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.
🌐
CodingNomads
codingnomads.com › python-301-use-a-list-in-stack-or-queue
Use a List in a Stack or Queue
Therefore, you are just using the Python list as a stack by limiting yourself to adding and removing elements only with .append() and .pop(), respectively. Just like the stack, you can also implement the functionality of a queue using a Python list:
🌐
Python.org
discuss.python.org › ideas
Initialize queue from an existing list - Ideas - Discussions on Python.org
July 5, 2022 - I am writing a code that uses queues and lists, and every time I need to create a queue from a list, what I do is l = [1, 2, 3, 4, 5] # existing list q = queue.Queue() for e in l: q.put(e) This actually works, but th…
🌐
STEMpedia
ai.thestempedia.com › home › examples › python queue implementation
Python Queue Implementation - Example Project
August 11, 2023 - Through real-world examples, you’ll ... empty') return None else: return myQueue.pop(0) def size(myQueue): return len(myQueue) # Initialize the queue myQueue = list() # each person to be assigned a code as P1, P2, P3,... element = input("Enter person’s code to enter in the queue: ...
🌐
Quora
quora.com › How-do-I-implement-a-queue-in-Python
How to implement a queue in Python - Quora
But you could essentially do it with composition. Create a class that has a list inside to do the storage. Provide methods that add to the end of the queue and remove from the front of the queue an...