python list as queue code example
Example 1: queue python
from queue import Queue
q = Queue()
q.size() # returns the current lenght of queue
q.empty() # returns True if empty, False otherwise
q.put(item)
q.get()
Example 2: python list as queue
# Demonstrate queue implementation using list
# Initializing a queue
queue = []
# Adding elements to the queue
queue.append('a')
queue.append('b')
print(queue)
# Removing elements from the queue
print("\nElements dequeued from queue")
print(queue.pop(0))
print(queue.pop(0))
print("\nQueue after removing elements")
print(queue)
# print(queue.pop(0)) will raise and IndexError as the queue is now empty
Example 3: queue in python
#creating a queue using list
#defining a list
my_queue =[]
#inserting the items in the queue
my_queue.append(1)
my_queue.append(2)
my_queue.append(3)
my_queue.append(4)
my_queue.append(5)
print("The items in queue:")
print(my_queue)
#removing items from queue
print(my_queue.pop(0))
print(my_queue.pop(0))
print(my_queue.pop(0))
print(my_queue.pop(0))
#printing the queue after removing the elements
print("The items in queue:")
print(my_queue)