dumping queue into list/array in python dumping queue into list/array in python python python

dumping queue into list/array in python


You're done with the parallel part and just want to get the results in a list, is that it? Then try:

list(my_queue.queue)

Example:

from queue import Queueq = Queue()for i in range(5):    q.put(i)l = list(q.queue)print(l)

Output:

[0, 1, 2, 3, 4]


Not sure whether it's the same problem, but I needed to do the same thing and ended up writing this. I am using threading.Thread and the Queue object in python 2.7. and just wanted to dump out a queue to a list.

def queue_to_list(q):    """ Dump a Queue to a list """    # A new list    l = []    while q.qsize() > 0:        l.append(q.get())    return l


I would go with the following solution:

from collections import dequeq = deque()for i in range(5):    q.append([i,i+10])listed_q = list(q)

Now you can easily access the values by indexing or slicing:

print listed_q[1]        # [1, 11]print listed_q[1][1]     # 11

Since list() creates a copy of q, you should keep an eye on the dimensionality of your queue. The time needed to do this operation grows the longer your queue is. An alternative approach can be found by using itertools.islice where you first slice the queue before you store the outcome in a list. Check out the following links (performance measures are also given there):

Use slice notation with collections.deque

How to slice a deque? [duplicate]