Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Put multiple items in a python queue

Tags:

python

queue

Suppose you have an iterable items containing items that should be put in a queue q. Of course you can do it like this:

for i in items:
    q.put(i)

But it feels unnecessary to write this in two lines - is that supposed to be pythonic? Is there no way to do something more readable - i.e. like this

q.put(*items)
like image 777
IARI Avatar asked Aug 13 '15 11:08

IARI


People also ask

What does queue () do in Python?

Queue in Python is a linear data structure with a rear and a front end, similar to a stack. It stores items sequentially in a FIFO (First In First Out) manner. You can think of it as a customer services queue that functions on a first-come-first-serve basis.

Can we use list as a queue in Python?

Implementation using list. List is a Python's built-in data structure that can be used as a queue. Instead of enqueue() and dequeue(), append() and pop() function is used.

What is the max size of queue in Python?

To answer your 1st question: for all intents and purposes, the max size of a Queue is infinite. The reason why is that if you try to put something in a Queue that is full, it will wait until a slot has opened up before it puts the next item into the queue.


2 Answers

Using the built-in map function :

map(q.put, items)

It will apply q.put to all your items in your list. Useful one-liner.


For Python 3, you can use it as following :

list(map(q.put, items))

Or also :

from collections import deque
deque(map(q.put, items))

But at this point, the for loop is quite more readable.

like image 118
FunkySayu Avatar answered Sep 22 '22 20:09

FunkySayu


What's unreadable about that?

for i in items:
    q.put(i)

Readability is not the same as "short", and a one-liner is not necessarily more readable; quite often it's the opposite.

If you want to have a q.put(*items)-like API, consider making a short helper function, or subclassing Queue.

like image 20
Cyphase Avatar answered Sep 23 '22 20:09

Cyphase