Skip to content
Related Articles

Related Articles

Dumping queue into list or array in Python
  • Last Updated : 31 Dec, 2020

Prerequisite: Queue in Python

Here given a queue and our task is to dump the queue into list or array. We are to see two methods to achieve the objective of our solution.

Example 1: 

In this example, we will create a queue using the collection package and then cast it into the list



Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to
# demonstrate queue implementation
# using collections.dequeue
   
from collections import deque
   
# Initializing a queue
q = deque()
   
# Adding elements to a queue
q.append('a')
q.append('b')
q.append('c')
  
# display the queue
print("Initial queue")
print(q,"\n")
  
# display the type
print(type(q))

chevron_right


Output:

Initial queue
deque(['a', 'b', 'c']) 

<class 'collections.deque'>

Let’s create a list and cast into it:

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# convert into list
li = list(q)
  
# display
print("Convert into the list")
print(li)
print(type(li))

chevron_right


Output:

Convert into the list
['a', 'b', 'c']
<class 'list'>

Example 2:

In this example, we will create a queue using the queue module and then cast it into the list.

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

from queue import Queue
  
# Initializing a queue
que = Queue()
  
# Adding elements to a queue
que.put(1)
que.put(2)
que.put(3)
que.put(4)
que.put(5)
  
# display the queue
print("Initial queue")
print(que.queue)
  
# casting into the list
li = list(que.queue)
print("\nConverted into the list")
print(li)

chevron_right


Output:

Initial queue
deque([1, 2, 3, 4, 5])

Converted into the list
[1, 2, 3, 4, 5]

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :