Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using map with queue.put()?

Tags:

python

To load a list into a queue in Python, I found this code snippet which failed to work. No items were added to the queue:

from queue import Queue
my_list = [1,2,3,4,5,6,7,8,9,10]
q = Queue()

# This code doesn't work
map(q.put, my_list)
q.qsize() # Returns zero, which is unexpected

The more verbose solution:

for num in my_list:
    q.put(num)
print(q.qsize())  # returns 10 as expected

works as expected. What am I missing here?

like image 260
max Avatar asked Feb 14 '26 02:02

max


1 Answers

map(q.put, my_list) just returns an iterator. Unless you iterate through it, your queue q wont be populated

>>> q = Queue()
>>> itr = map(q.put, my_list)
>>> q.qsize()
0
>>> _ = list(map(q.put, my_list))
>>> q.qsize()
10
like image 136
Sunitha Avatar answered Feb 15 '26 14:02

Sunitha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!