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
🌐
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 › python › queue-in-python
Queue in Python - GeeksforGeeks
May 29, 2026 - Python · 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) Output · Initial queue: ['a', 'b', 'c'] Elements dequeued from queue: a b c Queue after removing elements: [] Explanation: We added elements using append() and removed from the front using pop(0).
🌐
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 deque.popleft() | by mollihua | Medium
July 2, 2020 - def listpop(alist): ts = time.time() alist.pop(0) te = time.time() print("{:e}".format(te - ts))def dequepopleft(alist): q = collections.deque(alist) ts = time.time() q.popleft() te = time.time() print("{:e} seconds".format(te - ts))a = [x for x in range(10**6)]listpop(a) # output: 4.558802e-03 seconds dequepopleft(a) # output: 2.861023e-06 seconds · Python · Queue ·
🌐
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.
🌐
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.

🌐
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....
🌐
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.
Find elsewhere
🌐
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.
🌐
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()
🌐
TutorialsPoint
tutorialspoint.com › article › program-to-implement-a-queue-that-can-push-or-pop-from-the-front-middle-and-back-in-python
Program to implement a queue that can push or pop from the front, middle, and back in Python
Define a function pop_from_back() . ... Define a function show_queue() . This will take no input ... class Solution(): def __init__(self): self.array = [] def push_from_front(self, value): self.array.insert(0, value) def push_from_middle(self, value): self.array.insert(len(self.array) // 2, value) def push_from_back(self, value): self.array.append(value) def pop_from_front(self): return (self.array or [-1]).pop(0) def pop_from_middle(self): return (self.array or [-1]).pop((len(self.array) - 1) // 2) def pop_from_back(self): return (self.array or [-1]).pop() def show_queue(self): return self.array ob = Solution() ob.push_from_back(10) ob.push_from_back(20) ob.push_from_front(30) ob.push_from_middle(40) ob.push_from_front(50) print(ob.show_queue()) ob.pop_from_back() print(ob.show_queue()) ob.pop_from_front() print(ob.show_queue()) ob.pop_from_middle() print(ob.show_queue())
🌐
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 print(f"Executing {current_task}")
🌐
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 - In addition to the built-in data structures, you can also implement a custom queue class in Python. Here is one way to implement a basic queue: class Queue: def **init**(self): self.items = [] def size(self): return len(self.items) def enqueue(self, item): self.items.append(item) def dequeue(self): if self.size() == 0: return None return self.items.pop(0) To use it: q = Queue() q.enqueue(1) q.enqueue(2) q.enqueue(3) print(q.size()) # 3 print(q.dequeue()) # 1 print(q.dequeue()) # 2 ·
🌐
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) ...
🌐
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 []
🌐
W3Schools
w3schools.com › dsa › dsa_data_queues.php
DSA Queues
Python: queue = [] # Enqueue queue.append('A') queue.append('B') queue.append('C') print("Queue: ", queue) # Dequeue element = queue.pop(0) print("Dequeue: ", element) # Peek frontElement = queue[0] print("Peek: ", frontElement) # isEmpty isEmpty = not bool(queue) print("isEmpty: ", isEmpty) # Size print("Size: ", len(queue)) Try it Yourself » ·
🌐
Educative
educative.io › answers › how-to-implement-a-queue-in-python
How to implement a queue in Python
Queues in Python can be implemented using lists (with append() and pop(0)), the Queue module (using methods like put(), get(), and empty()), or the collections.deque module (using append() and popleft() for efficient operations).
🌐
AskPython
askpython.com › python-modules › python-queue
Python Queue Module - AskPython
February 26, 2020 - A simple solution would be to use Python’s list. We’ll use list.append(value) to insert elements into the queue, since insertion happens at the end, and remove elements using list.pop(0), since the first element is removed.
🌐
Intellipaat
intellipaat.com › home › blog › python queue tutorial: queue module, deque & priority queue (2026)
Python Queue: queue.Queue, deque & PriorityQueue Explained with Examples
May 7, 2026 - 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.