Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
community creator

How to implement a queue in Python

Abdul Samad

Queue is a linear data structure that stores items in a First-In/First Out(FIFO) manner. In queue, the data element that is inserted first will be removed first.

Operations that can be performed on the queue are:

  1. Enqueue: It adds an item to the queue. If the queue is full, then it is said to be an Overflow condition.

  2. Dequeue: It removes an item from the queue. The items are popped in the same order in which they are pushed. If the queue is empty, then it is said to be an Underflow condition.

  3. Front: It gives the front item from the queue.

  4. Rear: It gives the last item from the queue.

Note: The time complexity for all of the above operations is O(1).

1 of 5

Implementation

Queue in Python can be implemented in the following ways:

  1. list
  2. collections.deque
  3. queue.Queue
# implementing Queue using List :
q=[]
q.append(10)
q.append(100)
q.append(1000)
q.append(10000)
print("Initial Queue is:",q)
print(q.pop(0))
print(q.pop(0))
print(q.pop(0))
print("After Removing elements:",q)
Code to implement queue using list
# Implement Queue using List(Functions)
q=[]
def Enqueue():
    if len(q)==size: # check wether the stack is full or not
        print("Queue is Full!!!!")
    else:
        element=input("Enter the element:")
        q.append(element)
        print(element,"is added to the Queue!")
def dequeue():
    if not q:# or if len(stack)==0
        print("Queue is Empty!!!")
    else:
        e=q.pop(0)
        print("element removed!!:",e)
def display():
    print(q)
    size=int(input("Enter the size of Queue:"))
    while True:
        print("Select the Operation:1.Add 2.Delete 3. Display 4. Quit")
        choice=int(input())
        if choice==1:
            Enqueue()
        elif choice==2:
            dequeue()
        elif choice==3:
            display()
        elif choice==4:
            break
        else:
            print("Invalid Option!!!")
Code to implement queue using list
# implment queue using queue module
from queue import Queue
q=Queue(maxsize=4)
print("Initial Size Before Insertion:",q.qsize())
q.put('A')
q.put('AA')
q.put('AAA')
q.put('AAAA')
print("After Insertion:",q.qsize())
print("Queue is Full or Not:",q.full())
print("Size of Queue:",q.qsize())
print("Removing Elements:")
print(q.get())
print(q.get())
print(q.get())
print("Empty or Not??",q.empty())
print(q.get())
print("Empty or Not??",q.empty())
print("Size of Queue:",q.qsize())
Code to implement queue using queue module
from collections import deque
q=deque()
q.append(10)
q.append(100)
q.append(1000)
q.append(10000)
print("Initial Queue is:",q)
print(q.popleft())
print(q.popleft())
print("After Removing elements:",q)
Code to implement queue using deque module

RELATED TAGS

python
community creator
RELATED COURSES

View all Courses

Keep Exploring