Python Tutorial @ Home

#### Data Structures In Python

Data Structures In Python

# Python|Implementation Of Queue Data Structures

IMPLEMENTATION OF QUEUE IN PYTHON

The basic operations carried out are as follows:

Creating a Queue using List
Inserting an element in a Queue
Checking for an empty queue
Traversal / Display of elements
Deletion of elements from the Queue

Creating a Queue using List

Whenever we create a list in Python, it creates an address in memory and can store any number of heterogenous elements. Like a stack is created using the Python inbuilt function list[], in the same manner Queue is created. The Queue is also created using list() function.

Syntax:

Method:1
To create an empty queue
Queue=list()

Method:2
To create an empty queue
Queue=[]

Hence, Queue is created as a variable of list type and is an empty list or empty Queue as it does not contain any element.

Inserting an element into a Queue

Whenever an element is added in the queue it is added at the end/rear. append() method of list helps us to add an element in the queue.

Syntax:

queue.append(n)
where,

Algorithm to insert an element

1. Start
2. n=input(“Enter element to add “)
where n is value to add
3. queue.append(n)
4. stop

Deletion of the element from Queue

Before deleting an element it is important to check whether the queue is empty or not. if it is empty then an appropriate message should be displayed otherwise element will be deleted. To delete an element we use pop() method of list.

Syntax:

Queue.pop(0)
where,
0(zero) is position, i.e. first element

Once an element is deleted/removed from the front of the queue, it automatically reduces one index position, so we decrease one position down to the rear.

Algorithm to delete an element

Method:1

1. start
2. if(queue==[]):
print(“Queue is empty”)
goto step 4
3. n=queue.pop(0)
4. stop

Method:2

1. start
2. if not queue:
print(“Queue is empty”)
goto step 4
3. n=queue.pop(0)
4. stop

Method:3

1. start
2. if not len(queue):
print(“Queue is empty”)
goto step 4
3. n=queue.pop(0)
4. stop

Traversal of elemenst

1. start
2. n=len(queue)
n will store the length of queue (total elements)
3. for i in range(0,n):
print(queue[i])
4. stop

```#Queue implementation
q=[]
while True:
print("1. Insert");
print("2. Delete");
print("3. Display All/ Traversal")
print("4. Exit")
if(ch==1):
a=input("Enter any element ")
q.append(a)
elif(ch==2):
if(q==[]):
print("Underflow /  Queue is empty")
else:
print("poped element is ",q[0])
q.pop(0)
elif(ch==3):
n=len(q)
if(n==0):
print("queue is empty")
else:
for i in range(0,n):
print(q[i])
elif(ch==4):
print("End")
break
else:
print("Invalid choice")```

Important Pages