If you look at any python implementation of bfs, it always uses a "deque" (double ended queue) instead of a "list". The only difference being a deque is O(1) for popping the first element, if you used a normal list then that would be O(n). Answer from agentbobR on reddit.com
🌐
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.

🌐
Medium
medium.com › @mollihua › pop-first-element-of-a-queue-in-python-list-pop-0-vs-collections-deque-popleft-7991408e45b
Pop first element of a queue in Python — list.pop(0) vs ...
July 2, 2020 - Pop first element of a queue in Python — list.pop(0) vs deque.popleft() The time complexity of deque.popleft() is O(1), while the time complexity of list.pop(0) is O(k), as index 0 is considered an …
🌐
CodingNomads
codingnomads.com › python-301-use-a-list-in-stack-or-queue
Use a List in a Stack or Queue
In this example, you're using two ... the end of the collection. .pop(0), used with an argument of 0, allows you to remove the first element from the collection....
🌐
Readthedocs
pynote.readthedocs.io › en › latest › DataTypes › Stack_Queue.html
Stacks and Queues in Python — pynotes documentation
We can use the same functions to implement a Queue. The pop function optionally takes the index of the item we want to retrieve as an argument. So we can use pop with the first index of the list i.e. 0, to get queue-like behavior.
🌐
W3Schools
w3schools.com › python › python_dsa_queues.asp
Queues with Python
Using a Python list as a queue: 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 » ·
🌐
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 for append and pop operations as compared to list which provides O(n) time complexity.
🌐
Medium
medium.com › @shuangzizuobh2 › how-well-do-you-code-python-9bec36bbc322
How slow is python list.pop(0) ?. An empirical study on python list.pop… | by Hj | Medium
September 27, 2023 - line 19: queue = list([root]) line 21: cur = queue.pop(0) and here is the profiling results. The list.pop(0) operation is almost 1000 times slower than deque.popleft. Consequently, the whole program finishes with twice the time. This is the difference between O(1) time complexity function v.s. O(n) one. Python list.pop(0) is extremely slow for a large list.
Find elsewhere
🌐
HotExamples
python.hotexamples.com › examples › util › Queue › pop › python-queue-pop-method-examples.html
Python Queue.pop Examples, util.Queue.pop Python Examples - HotExamples
def breadthFirstSearch(problem): """Search the shallowest nodes in the search tree first.""" "*** YOUR CODE HERE ***" # util.raiseNotDefined() from util import Queue q = Queue() q2 = Queue() q2.push([]) q.push([problem.getStartState()]) visited = [] visited.append(problem.getStartState()) if (problem.isGoalState(problem.getStartState())): return [] x = 1 while (q.isEmpty() == False): path = q.pop() path2 = q2.pop() top = path[-1] if (problem.isGoalState(top)): return path2 successors = problem.getSuccessors(top) for i in range(len(successors)): if (successors[i][0] not in visited): # path.append(successors[i][1]) addpath = list(path) addpath.append(successors[i][0]) addpath2 = list(path2) addpath2.append(successors[i][1]) q.push(addpath) q2.push(addpath2) visited.append(successors[i][0]) # if(problem.isGoalState(successors[i][0])): # return addpath2 return []
🌐
Stack Overflow
stackoverflow.com › questions › 66727296 › how-to-pop-continuos-values-from-a-queue
python - How to pop continuos values from a queue - Stack Overflow
March 20, 2021 - The code is followed by the output which is empty for function waiting as all the values are popped. Class myQueue(): def enqueue(self, data,vip): if vip==1: self.queue2.insert(0, data) else: self.queue.insert(0,data) def dequeue(self): while len(self.queue2) > 0: return self.queue2.pop() else: return self.queue.pop() def waiting(self): self.queue.reverse() self.queue2.reverse() self.queue2.extend(self.queue) return self.queue2 myQueue = Queue() myQueue.enqueue(10,0) # return True myQueue.enqueue(5,1) myQueue.enqueue(6,0) myQueue.enqueue(11,1) print(myQueue.waiting())
🌐
Google Groups
groups.google.com › g › comp.lang.python › c › kiHYf5N0iz8
list.pop(0) vs. collections.dequeue
There are perfectly valid use cases for wanting a list over a > dequeue without having to pay O(N) for pop(0). Maybe we are just > quibbling over the meaning of "rarely." I was speaking from my own point of view. I've written several tenths of thousands of lines of Python code in the last seven years, mostly related to data manipulation, web applications and operating system interaction but also GUI stuff and scientific code.
🌐
Educative
educative.io › answers › how-to-implement-a-queue-in-python
How to implement a queue in Python
If you want to peek at the front of the queue, you can use the index 0. The -1 index refers to accessing the last element in the queue. In Python, negative indexes start from the end of the list. So: queue[-1] will return the last element in the queue (the rightmost side in a deque). ... 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, ...
🌐
Mimo
mimo.org › glossary › python › pop()
Python Pop Method: Essential Data Manipulation techniques
In Python, pop() is also ideal for scenarios where you need iterate through a list while removing items. For example, consider task scheduling or processing a queue of actions. ... tasks = ["write", "debug", "test"] while tasks: current_task = tasks.pop(0) # Remove and return the first task ...
🌐
Python
docs.python.org › 3 › library › queue.html
queue — A synchronized queue class
Remove and return an item from the queue. If optional args block is true and timeout is None (the default), block if necessary until an item is available. If timeout is a positive number, it blocks at most timeout seconds and raises the Empty ...
🌐
Analytics Vidhya
analyticsvidhya.com › home › queue in python: an in-depth guide
Queue in Python: An In-Depth Guide
August 12, 2024 - Python lists can be used to implement a queue. However, using lists for queues is not efficient for large datasets because removing elements from the front of a list is an O(n) operation. class ListQueue: def __init__(self): self.queue = [] def enqueue(self, item): self.queue.append(item) print(f"Enqueued: {item}") def dequeue(self): if self.is_empty(): raise IndexError("Dequeue from an empty queue") item = self.queue.pop(0) print(f"Dequeued: {item}") return item def peek(self): if self.is_empty(): raise IndexError("Peek from an empty queue") print(f"Peek: {self.queue[0]}") return self.queue[0] def is_empty(self): return len(self.queue) == 0 def size(self): print(f"Size: {len(self.queue)}") return len(self.queue) def clear(self): self.queue = [] print("Queue cleared") # Example usage lq = ListQueue() lq.enqueue(1) lq.enqueue(2) lq.peek() lq.dequeue() lq.size() lq.clear()
🌐
Board Infinity
boardinfinity.com › blog › queue-in-python
Queue in Python | Board Infinity
August 9, 2025 - ... Python's built-in module Queue is used to implement queues. queue. Queue(maxsize) sets a variable's initial value to maxsize, its maximum size. An infinite queue is indicated by a maxsize of zero "0." The FIFO rule is used in this queue.
🌐
Great Learning
mygreatlearning.com › blog › it/software development › python queue
Python Queue
October 14, 2024 - class Queue: def __init__(self): self.queue = list() def add_element(self,val): # Insert method to add element in the queue if val not in self.queue: self.queue.insert(0,val) return True return False # Pop method to delete element from the queue def remove_element(self): if len(self.queue)>0: return self.queue.pop() return ("Queue is Empty") que = Queue() que.add_element("January") que.add_element("February") que.add_element("March") que.add_element("April") print(que) print(que.remove_element()) print(que.remove_element()) ... Sorting a queue becomes important in some scenarios where we need to perform specific operations. It can be done in Python by various methods.
🌐
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
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)