Convert a List to a Queue in Python

avatar

Borislav Hadzhiev

Last updated: Jun 16, 2022

banner

Photo from Unsplash

Convert a List to a Queue in Python #

Use the collections.deque class to convert a list to a queue in Python, e.g. deq = deque(my_list). The deque class can be passed an iterable, such as a list, and initializes a new deque object.

main.py
from collections import deque my_list = [1, 2, 3] # ✅ convert list to queue deq = deque(my_list) print(deq) # 👉️ deque([1, 2, 3]) deq.append(4) print(deq) # 👉️ deque([1, 2, 3, 4]) print(deq.pop()) # 👉️ 4 print(deq.popleft()) # 👉️ 1

The collections.deque class takes an iterable and initializes a deque object (a double-ended queue).

The class has atomic append(), implements the popleft() method and supports indexing and membership testing.

If you need to use the queue module to create your queue, use a for loop to convert the list to a queue.

main.py
import queue my_list = [1, 2, 3] q = queue.Queue() for item in my_list: q.put(item) print(q.queue) # 👉️ deque([1, 2, 3])

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

The queue attribute on the queue points to a deque object which is much more full-featured.

You should only be using the queue module if you are running your code in a multi-threaded environment.

Here are some of the most commonly used methods the deque class implements.

main.py
from collections import deque my_list = [1, 2, 3] deq = deque(my_list) # 👇️ add a value to the right side of the deque deq.append(4) # 👇️ add a value to the left side of the deque deq.appendleft(0) # 👇️ extend the right side of the deque by appending the items from the iterable deq.extend([5, 6]) # 👇️ remove and return an element from the right side of the deque print(deq.pop()) # 👉️ 6 # 👇️ remove and return an element from the left side of the deque print(deq.popleft()) # 👉️ 0 print(deq) # 👉️ deque([1, 2, 3, 4, 5]) deq.clear() print(deq) # 👉️ 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.