How to put multiple items in a Queue in Python

avatar

Borislav Hadzhiev

Last updated: Jun 16, 2022

banner

Photo from Unsplash

Put multiple items in a Queue in Python #

To put multiple items in a queue in Python:

  1. Use a for loop to iterate over an iterable or a range.
  2. On each iteration call the put() method on the iterable.
  3. Pass the item to the put() method.
main.py
import queue q = queue.Queue() my_list = list(range(10)) print(my_list) # 👇️ iterate over list and put each item in the queue for item in my_list: q.put(item) print(q.queue) # 👉️ deque([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) for item in q.queue: print(item) # 👉️ 0 1 2 3 4 ...

We used a for loop to iterate over a list containing 10 items and used the put() method to put each item in the queue.

The Queue.put method puts an item in the queue.

You can also use a range if you need to put N items in the queue.

main.py
import queue q = queue.Queue() # 👇️ iterate over range and put each item in the queue for item in range(10): q.put(item) print(q.queue) # 👉️ deque([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) for item in q.queue: print(item) # 👉️ 0 1 2 3 4 ...

If you use a deque object, you can pass an iterable directly to the extend() method.

main.py
from collections import deque deq = deque() my_list = list(range(10)) deq.extend(my_list) print(deq) # 👉️ deque([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) for item in deq: print(item) # 0 1 2 3 4 ...

We used the collections.deque class to create a deque object.

The extend method takes an iterable as an argument and extends the right side of the deque by appending the items from the iterable.

You can also use a for loop with the append() method.

main.py
from collections import deque deq = deque() print(deq) my_list = list(range(10)) for item in my_list: deq.append(item) print(deq) # 👉️ deque([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) for item in deq: print(item) # 👉️ 0 1 2 3 4 ...

The append method takes a value and adds it to the right side of the deque.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.