SoFunction
Updated on 2024-12-20

Python Queue Definition and Usage Examples

This article example describes the definition and use of Python queues. Shared for your reference, as follows:

Although Python has its own queue module, we just need to introduce the module when we use it, but in order to better understand the queue, the queue itself will be implemented a little.

Queue is a data structure, it is characterized by first-in-first-out, that is, the end of the queue to add an element, the head of the queue to remove an element, similar to the shopping mall queue checkout, the first to come to the first person to receive the bill, and later at the end of the queue. In our daily life, sending SMS will use the queue. The following is the Python implementation of the queue code:

#!/usr/bin/python
#coding=utf-8
class Queue(object) :
 def __init__(self, size) :
   = size
   = []
 def __str__(self) :
  return str()
 # Get the current length of the queue
 def getSize(self) :
  return len()
 # Into the queue, if the queue is full return -1 or throw an exception, otherwise insert the element into the end of the queue
 def enqueue(self, items) :
  if () :
   return -1
   #raise Exception("Queue is full")
  (items)
 # Out of queue, returns -1 if the queue is empty or throws an exception, otherwise returns the head element of the queue and removes it from the queue
 def dequeue(self) :
  if () :
   return -1
   #raise Exception("Queue is empty")
  firstElement = [0]
  (firstElement)
  return firstElement
 #Judge the queue full
 def isfull(self) :
  if len() ==  :
   return True
  return False
 #Judge the queue empty
 def isempty(self) :
  if len() == 0 :
   return True
  return False

Here is the test code for this queue class .py file:

if __name__ == '__main__' :
 queueTest = Queue(10)
 for i in range(10) :
  (i)
 print ()
 print queueTest
 print ()
 for i in range(5) :
  print ()
 print ()
 print queueTest
 print ()

Test results:

More about Python related content can be viewed on this site topic: thePython Data Structures and Algorithms Tutorial》、《Summary of Python function usage tips》、《Summary of Python string manipulation techniques》、《Python introductory and advanced classic tutorialsand theSummary of Python file and directory manipulation techniques

I hope that what I have said in this article will help you in Python programming.