CodersZone logo

Queue Implementation in Python

Queue is a linear data structure that stores items in First In First Out (FIFO) manner. With a queue the least recently added item is removed first. A good example of queue is any queue of consumers for a resource where the consumer that came first is served first.
Operations associated with queue are:
  1. Enqueue: Adds an item to the queue. If the queue is full, then it is said to be an Overflow condition. Time Complexity : O(1)
  2. Dequeue: 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 – Time Complexity : O(1)
  3. Front: Get the front item from queue – Time Complexity : O(1)
  4. Rear: Get the last item from queue – Time Complexity : O(1)

Algorithm

    Enqueue Operation Algorithm

    1. check if the queue is full
    2. for the first element, set the value of FRONT to 0
    3. increase the REAR index by 1
    4. add the new element in the position pointed to by REAR
    5. Returns success.

    Dequeue Operation Algorithm

    1. check if the queue is empty
    2. return the value pointed by FRONT
    3. increase the FRONT index by 1
    4. for the last element, reset the values of FRONT and REAR to -1
    5. Returns success.

Code

                # Python program to demonstrate queue implementation using list

                # Initializing a queue
                queue = []
                
                # Adding elements to the queue
                queue.append('a')
                queue.append('b')
                queue.append('c')
                
                print("Initial queue")
                print(queue)
                
                # Removing elements from the queue
                print("\nElements dequeued from queue")
                print(queue.pop(0))
                print(queue.pop(0))
                print(queue.pop(0))
                
                print("\nQueue after removing elements")
                print(queue)
                
                # Uncommenting print(queue.pop(0))
                # will raise and IndexError
                # as the queue is now empty
                
            

Output

                
Initial queue
['a', 'b', 'c']
Elements dequeued from queue
a
b
c
Queue after removing elements
[]
See the same program in Java See the same program in C