Implement Queue using List in Python
In this tutorial, we will learn about the Queue data structure and how to implement it using the List in Python.
Queue using list – Python
There are two types of Data structures – Linear and non-linear. Under the linear category, you have arrays, linked lists, stacks, and queues. Each data structure differs in terms of the functionality it provides. Queues provide the functionality of FIFO (First in, First out). Take the analogy of your assembly lines in school or anywhere else where you have seen queues of people to visualize how the data will be processed in the compiler.
The first data that you will insert in the queue will be the first one to be processed, and it will be on the front and the first one to give output. This order will continue for further data. Queues are excessively used in BFS Algorithms of Graphs
.
Now, let’s implement the queue functionality using the List in Python.
queue = [] queue.append('Chandragupta') queue.append('Bindusar') queue.append('Ashoka') print("Queue after inserting data") print(queue) print("\nElements removed from queue\n") print("First -> ",queue.pop(0)) print("Second -> ",queue.pop(0)) print("Third -> ",queue.pop(0)) print("\nQueue after removing elements") print(queue)
Queue after inserting data ['Chandragupta', 'Bindusar', 'Ashoka'] Elements removed from queue First -> Chandragupta Second -> Bindusar Third -> Ashoka Queue after removing elements []
As you can see, I have first inserted the name “Chandragupta,” which is the first to be removed. The same order goes for all other data.
We have coded the basic functionality of Queue
using List
. Here, we can not implement all the features of Queues which is provided in Queue Library
. To use all the features, it is advised to use the library as it is the efficient approach for large and complex queues. You can define a class for implementing the features of queues using a list, but that’s not an efficient approach as you have to write the functions yourself in the class.
Leave a Reply