When the pop() method of a list is used [...] in class Queue it returns the 1st element.

No, it does not. It still returns the last element of the list. You should not look at dequeue and pop, you should instead concentrate on the Queue.enqueue and Stack.push methods.

The Stack class appends to the items list, so puts the new element at the end:

def push(self, item):
    self.items.append(item)

while the Queue inserts at the start of the items list:

def enqueue(self, item):
    self.items.insert(0,item)

So when you pop from the stack, you remove the element that was last added. When you pop from the queue, you remove the element that was first added, as everything else was inserted in front of it.

Put differently, the Queue hold items in chronological order (newest item is at the start of the list), while the Stack holds them in reverse chronological order (newest item is at the end of the list). Popping still removes the last element from the list.

Answer from Martijn Pieters on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org β€Ί python β€Ί queue-in-python
Queue in Python - GeeksforGeeks
December 11, 2025 - There are various ways to implement a queue in Python by following ways: Lists can be used as queues, but removing elements from front requires shifting all other elements, making it O(n). ... q = [] q.append('a') q.append('b') q.append('c') print("Initial queue:", q) print("Elements dequeued from queue:") print(q.pop(0)) print(q.pop(0)) print(q.pop(0)) print("Queue after removing elements:", q)
🌐
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: ... queue = [] # Enqueue queue.append('A') queue.append('B') queue.append('C') print("Queue: ", queue) # Peek frontElement = queue[0] print("Peek: ", frontElement) # Dequeue poppedElement = queue.pop(0) print("Dequeue: ", poppedElement) print("Queue after Dequeue: ", queue) # isEmpty isEmpty = not bool(queue) print("isEmpty: ", isEmpty) # Size print("Size: ", len(queue)) Try it Yourself Β»
Discussions

Best way to continuously pop elements from a queue until condition is reached
reverse the while, i.e. len(queue) first. Note that the > 0 is not required, just len(queue) More on reddit.com
🌐 r/learnpython
5
2
April 23, 2024
data structures - Why does, in python, Stack's pop method and Queue's dequeue method behave differently when both have same code? - Stack Overflow
When the pop() method of a list is used in class Stack, it returns the last element of the list (head of the stack) while in class Queue it returns the 1st element. Can anybody explain me the reason More on stackoverflow.com
🌐 stackoverflow.com
Implementing an efficient queue in Python - Stack Overflow
I have been trying to implement a queue in Python, and I've been running into a problem. I am attempting to use lists to implement the queue data structure. However I can't quite figure out how to ... More on stackoverflow.com
🌐 stackoverflow.com
python - Popping items from queue does not delete all of them - Stack Overflow
currently i am learning about stacks and queues. Tried to implement new knowledge, but can't understand why the popping doesn't remove all elements from my queue, only half of them. In this code i ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Python
docs.python.org β€Ί 3 β€Ί library β€Ί queue.html
queue β€” A synchronized queue class
February 23, 2026 - collections.deque is an alternative implementation of unbounded queues with fast atomic append() and popleft() operations that do not require locking and also support indexing. ... Β© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2.
🌐
Reddit
reddit.com β€Ί r/learnpython β€Ί best way to continuously pop elements from a queue until condition is reached
r/learnpython on Reddit: Best way to continuously pop elements from a queue until condition is reached
April 23, 2024 -

I have a deque that consists of datetime objects (the rightmost elements will always be newer) and I'm trying to write some logic to pop items older than n seconds off the queue. I have it sort of functioning, but my while loop depends on looking at the -1 element of the queue, which doesn't always exist (in the case where it has been emptied because all items in the queue were older than the threshold). I can get around it with some try/except stuff or more conditionals, but none of that seems very pythonic.

while True:
    targettime = datetime.now() - timedelta(seconds=5 * 60)
    while queue[-1] >= targettime and len(queue) > 0:
        queue.pop()
    if len(queue) == 0:
        do_work()
    time.sleep(60)

Any advice on how to handle this better? I'm open to entirely new solutions as well, using a deque seemed like the best approach but now I'm not so sure.

🌐
Great Learning
mygreatlearning.com β€Ί blog β€Ί it/software development β€Ί python queue
Python Queue
October 14, 2024 - The built-in list of methods in ... methods in Python are the insert() and pop() functions that are used to add and remove elements from the queue....
🌐
Real Python
realpython.com β€Ί python-deque
Python's deque: Implement Efficient Queues and Stacks – Real Python
January 12, 2026 - Use a Python deque to efficiently append and pop elements from both ends of a sequence, build queues and stacks, and set maxlen for history buffers.
Find elsewhere
🌐
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 - from collections import deque dq = deque() dq.append(1) dq.append(2) dq.appendleft(3) print(dq) # deque([3, 1, 2]) dq.pop() # 2 dq.popleft() # 3 Β· deque provides a thread-safe version called deque.deque that can be used in multi-threaded programs. ... In addition to the built-in data structures, you can also implement a custom queue class in Python.
🌐
Educative
educative.io β€Ί answers β€Ί how-to-implement-a-queue-in-python
How to implement a queue in Python
To get elements from the other side of the deque (the right end), you can use the pop() method, which removes and returns the element at the end of the queue. ... Learn the basics with our engaging course!
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
🌐
Board Infinity
boardinfinity.com β€Ί blog β€Ί queue-in-python
Queue in Python | Board Infinity
August 9, 2025 - In the same order that they are pushed, the items are popped. It's called an underflow condition if the queue is empty. Time Complexity: O (1) Front: Get the first item in the queue; Time Complexity: O (1) Rear: Obtain the last item in the queue.
🌐
Stack Overflow
stackoverflow.com β€Ί questions β€Ί 61294285 β€Ί popping-items-from-queue-does-not-delete-all-of-them
python - Popping items from queue does not delete all of them - Stack Overflow
queue = [] # or a line of customers before they have arrived. print("Empty line: ", queue) for number in range(1, 11): queue.append(number) # here i add 10 customers to the line. print("Line after 10 people have arrived: ", queue) for i in range(0, len(queue)): print("Removed customer iD: ", queue.pop()) # here i tried to remove all customers
🌐
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 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. The pop operation can be used to remove the front element (the last element of the list).
🌐
GeeksforGeeks
geeksforgeeks.org β€Ί python β€Ί stack-and-queues-in-python
Stack and Queues in Python - GeeksforGeeks
May 9, 2022 - So, we prefer the use of dequeue over list, which was specially designed to have fast appends and pops from both the front and back end. Let's look at an example and try to understand queue using collections.deque: ... # Python code to demonstrate Implementing # Queue using deque from collections import deque queue = deque(["Ram", "Tarun", "Asif", "John"]) print(queue) queue.append("Akbar") print(queue) queue.append("Birbal") print(queue) print(queue.popleft()) print(queue.popleft()) print(queue)
🌐
Programmathically
programmathically.com β€Ί home β€Ί software design β€Ί the queue in python
The Queue in Python - Programmathically
June 6, 2021 - The simplest way to implement a Python queue is through a list. You can dequeue items from a list using the pop method.
🌐
Real Python
realpython.com β€Ί queue-in-python
Python Stacks, Queues, and Priority Queues in Practice – Real Python
December 1, 2023 - Why not use a Python list instead of collections.deque as a building block for your FIFO queue? Both sequences allow for enqueuing elements with their .append() methods rather cheaply, with a small reservation for lists, which will occasionally require copying all elements to a new memory location when their number exceeds a certain threshold. Unfortunately, dequeuing an element from the front of a list with list.pop(0), or equivalently inserting one with list.insert(0, element), is far less efficient.
🌐
Replit
replit.com β€Ί home β€Ί discover β€Ί how to use pop() in python
How to use pop() in Python | Replit
February 13, 2026 - Inside the loop, stack.pop() removes and returns the last item added. This demonstrates the Last-In, First-Out (LIFO) principle. "third task" is added last, so it's processed first.
🌐
Readthedocs
pynote.readthedocs.io β€Ί en β€Ί latest β€Ί DataTypes β€Ί Stack_Queue.html
Stacks and Queues in Python β€” pynotes documentation
We can add items to a stack using the push operation and retrieve items using the pop operation. With queues, we add items using the enqueue operation and retrieve items using the dequeue operation. In Python, we can implement stacks and queues just by using the built-in List data structure.
🌐
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
🌐
Intellipaat
intellipaat.com β€Ί home β€Ί blog β€Ί queue in python – implementation explained
Queue in Python: How to Implement Queue in Python
October 14, 2025 - In this script, the enqueue() function adds an element to the queue by appending it to the end of the queue list. The dequeue() function removes the first element from the queue using the pop(0) method.