Reputation: 1377
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)
Upvotes: 15
Views: 23593
Reputation: 11
q.extend(items)
Should be simple and Pythonic Enough
If you want it at the front of the queue
q.extendleft(items)
Python Docs:
https://docs.python.org/2/library/collections.html#collections.deque.extend
Upvotes: -3
Reputation: 8061
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.
Upvotes: 16
Reputation: 12002
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
.
Upvotes: 2