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)
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.
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With