Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Implementing a Simple Queue Class in Python

Implementing a Simple Queue Class in Python

Document Object Reference Manual Python3 Examples

A queue is a first-in-first-out (FIFO) data structure. We can use a Python list to implement a simple queue class with the following basic operations:

  1. enqueue(item): Add an element to the end of the queue.
  2. dequeue(): Remove and return the first element of the queue.
  3. is_empty(): Check whether the queue is empty.
  4. size(): Return the number of elements in the queue.

Example

class

Queue

:

   

def

init

(

self

)

:

       

self

.

items

=

[

]

   

def

is_empty

(

self

)

:

       

return

self

.

items

==

[

]

   

def

enqueue

(

self

,

item

)

:

       

self

.

items

.

append

(

item

)

   

def

dequeue

(

self

)

:

       

if

self

.

is_empty

(

)

:

           

return

None

       

return

self

.

items

.

pop

(

0

)

   

def

size

(

self

)

:

       

return

len

(

self

.

items

)

Code analysis:

Output result:

Example

Example usage

q

=

Queue

(

)

q.

enqueue

(

1

)

q.

enqueue

(

2

)

q.

enqueue

(

3

)

print

(

q.

dequeue

(

)

)

 

Output: 1

print

(

q.

size

(

)

)

   

Output: 2

print

(

q.

is_empty

(

)

)

Output: False

In this example we first create a queue q, then add the elements 1、2 and 3 one after another. Next we call the dequeue method to remove and return the first element of the queue 1. Finally we check the queue size and whether it is empty, printing 2 and False。

Document Object Reference Manual Python3 Examples