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 › implementation-of-queue-using-list-in-python
Implementation of Queue using List in Python - GeeksforGeeks
July 23, 2025 - Dequeue: To dequeue an element from the queue, do the following: 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 empt
🌐
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]
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
Queues can be implemented by using arrays or linked lists. Queues can be used to implement job scheduling for an office printer, order processing for e-tickets, or to create algorithms for breadth-first search in graphs.
🌐
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
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) CodeLens 1 shows the Queue class in action as we perform the sequence of operations from Table 1.
🌐
GeeksforGeeks
geeksforgeeks.org › queue-in-python
Queue in Python - GeeksforGeeks
July 9, 2024 - However, lists are quite slow for ... simulates a queue using a Python list. It adds elements 'a', 'b', and 'c' to the queue and then dequeues them, resulting in an empty queue at the end....
🌐
YouTube
youtube.com › watch
Queue Implementation Using List | Data Structure | Python Tutorials - YouTube
In this Python Programming video tutorial you will learn about queue data structure and how to implement that using list in detail.Data structure is a way of...
Published   September 2, 2020
🌐
Techie Delight
techiedelight.com › home › queue › queue implementation in python
Queue Implementation in Python | Techie Delight
September 12, 2025 - Following is a simple example demonstrating the usage of deque to implement queue data structure in Python: ... Average rating 4.84/5. Vote count: 163 · No votes so far! Be the first to rate this post. We are sorry that this post was not useful for you! Tell us how we can improve this post? Submit Feedback ... Thanks for reading. To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
🌐
Sanfoundry
sanfoundry.com › python-program-implement-queue-data-structure-using-linked-list
Python Program to Implement Queue using Linked List - Sanfoundry
May 30, 2022 - Problem Description The program creates a queue and allows the user to perform enqueue and dequeue operations on it. Problem Solution 1. Create a class Node with instance variables data and next.
Find elsewhere
🌐
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 - This differs from stacks, which follow last-in, first-out (LIFO). Queues are useful when the order of operations matters, like: ... In Python, queues can be implemented using lists or the collections.deque object.
🌐
YouTube
youtube.com › watch
QUEUE IMPLEMENTATION USING LISTS IN PYTHON || QUEUE OPERATIONS || DSA USING PYTHON - YouTube
DATA STRUCTURES USING PYTHONhttps://www.youtube.com/playlist?list=PLLOxZwkBK52Apt7hZ--6D5q1QY6uQ6vgtPYTHON TUTORIAL FOR BEGINNERS IN 11 HOURS (in ENGLISH) ||...
Published   March 3, 2023
🌐
Educative
educative.io › answers › how-to-implement-a-queue-in-python
How to implement a queue in Python
In Python lists, we can use the append() method to add elements to the end of the list, effectively simulating the enqueue operation and the pop() method to remove elements from the beginning with an index of 0, effectively simulating the dequeue ...
🌐
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 - When it is required to implement a queue data structure using a linked list, a method to add (enqueue operation) elements to the linked list, and a method to delete (dequeue operation) the elements of the linked list are defined.
🌐
PythonForBeginners
pythonforbeginners.com › home › implement queue in python
Implement Queue in Python - PythonForBeginners.com
July 16, 2021 - In this way, the most recent element will always be at the end of the linked list and the oldest element will always be at the front of the linked list.After inserting the element to the queue, we will also get the size of the queue and increment the size by 1. The Enqueue operation can be implemented using linked lists in python as follows.
🌐
GeeksforGeeks
geeksforgeeks.org › python › implementation-of-queue-using-linked-list-in-python
Implementation of Queue using Linked List in Python - GeeksforGeeks
July 23, 2025 - class Node: def __init__(self, key): self.key = key self.next = None class MyQueue: def __init__(self): self.front = None self.rear = None self.size = 0 # Enqueue: Add an element to the rear of the queue def enqueue(self, x): temp = Node(x) if self.rear is None: self.front = temp self.rear = temp else: self.rear.next = temp self.rear = temp self.size += 1 # Dequeue: Remove and return the element # from the front of the queue def dequeue(self): if self.front is None: return None # Store the front node's value res = self.front.key # Move the front pointer to the next node self.front = self.front
🌐
Brainly
brainly.in › computer science › secondary school
write a python program to implement queue using a list data structure.​ - Brainly.in
October 25, 2020 - Python Program to Implement Queue Data Structure using Linked... Create a class Node with instance variables data and next. Create a class Queue with instance variables head and last.
🌐
TutorialsPoint
tutorialspoint.com › program-to-implement-queue-in-python
Python Data Structure - Queue
April 15, 2021 - class Queue: def __init__(self): self.queue = list() def addtoq(self,dataval): # Insert method to add element if dataval not in self.queue: self.queue.insert(0,dataval) return True return False # Pop method to remove element def removefromq(self): ...
🌐
Codez Up
codezup.com › home › write a program to implement queue class – python
Write a Program to implement Queue Class - Python | Codez Up
March 13, 2021 - Let’s create a constructor first which accepts one argument as size which initializes the size of the queue and a list to store the elements in the queue.
🌐
Programiz
programiz.com › dsa › queue
Queue Data Structure and Implementation in Java, Python and C/C++
# Queue implementation in Python class Queue(): def __init__(self, k): self.k = k self.queue = [None] * k self.head = self.tail = -1 # Insert an element into the queue def enqueue(self, data): if (self.tail == self.k - 1): print("The queue is full\n") elif (self.head == -1): self.head = 0 self.tail = 0 self.queue[self.tail] = data else: self.tail = self.tail + 1 self.queue[self.tail] = data # Delete an element from the queue def dequeue(self): if (self.head == -1): print("The queue is empty\n") elif (self.head == self.tail): temp = self.queue[self.head] self.head = -1 self.tail = -1 return tem
🌐
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 the ...