How to convert a list to queue? So that operations like enqueue or dequeue an be carried out. I want to use to the list to remove the top most values and i believe it can be done using queues.
5 Answers
pop from the front of a list is not very efficient as all the references in the list need to be updated.
deque will allow you do queue like operations efficiently
>>> from collections import deque
>>> deque([1,2,3,4])
deque([1, 2, 3, 4])
2 Comments
Since I was looking for an answer to this question while using queue.Queue, I thought I should share my findings. It is possible to convert a list into a queue using queue.queue.
import queue
l = [i for i in range(1000)]
q = queue.Queue()
[q.put(i) for i in l]
q2 = queue.Queue()
q2.queue = queue.deque(l)
After this code has been run, q and q2 are two different queues that contain the exact same entries, but with the second method being >300 times faster on my machine.
Not related to the question, but the opposite can be done by l = list(q.queue) if q is an instance of queue.Queue. Hope this saves you some trouble!
This was all tested in python 3.5.2.
1 Comment
just use pop()
>>> x = [1,2,3]
>>> x.pop(0)
1
>>> x
[2,3]
1 Comment
You can use a list as a queue. If you want a fifo queue, just use .append() to add and .pop(0) to remove. For a lifo queue (i.e a stack), use .append() to add and .pop() to remove.
You should use collections.deque when implementing a fifo-queue which was designed specifically for this purpose. .pop(0) is a O(n) operation. Using a list as a stack is just fine.
FIFO Queue:
In [1]: q = range(15)
In [2]: q.pop(0)
Out[2]: 0
In [3]: q.pop(0)
Out[3]: 1
In [4]: q.pop(0)
Out[4]: 2
LIFO Queue:
In [5]: q = range(10)
In [6]: q.pop()
Out[6]: 9
In [7]: q.pop()
Out[7]: 8
In [8]: q.pop()
Out[8]: 7
3 Comments
collections.deque is the standard answer, though it's not abstracted terribly well.
There's also https://pypi.python.org/pypi/linked_list_mod/ , if you're willing to sacrifice a little speed for better abstraction. collections.deque is faster. linked_list_mod lets you pass an iterable to the constructor; the provided lifo and fifo modules do not, but could trivially be modified to do so.