Put multiple items in a python queue

Suppose you have iterative items items that should be queued q . Of course you can do it like this:

 for i in items: q.put(i) 

But it makes no sense to write this in two lines - should it be pythonic? Is there no way to make something more readable - for example, this

 q.put(*items) 
+6
source share
3 answers

Using the built-in map function:

 map(q.put, items) 

It will apply q.put to all of your items in your list. Useful single line.


For Python 3, you can use it like:

 list(map(q.put, items)) 

Or also:

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

But at this point, the for loop becomes more readable.

+10
source
 q.extend(items) 

It should be simple and enough Pythonic

If you want him in front of the line

 q.extendleft(items) 

Python docs:

https://docs.python.org/2/library/collections.html#collections.deque.extend

+1
source

What is unreadable about this?

 for i in items: q.put(i) 

Readability is not the same as β€œshort”, and a single-line font is not necessarily readable; often the opposite.

If you want to have the q.put(*items) API, consider creating a short helper function or Queue subclasses.

0
source

All Articles