Implementing a Simple Queue Class in Python
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:
enqueue(item): Add an element to the end of the queue.dequeue(): Remove and return the first element of the queue.is_empty(): Check whether the queue is empty.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:
__init__The method initializes an empty listitems, which stores the elements of the queue.is_emptyThe method checks whether the queue is empty; if theitemslist is empty it returnsTrue; otherwise, returnsFalse。enqueueThe method adds the elementitemtoitemsto the end of the list.dequeueThe method removes and returns theitemsfirst element of the list. If the queue is empty, it returnsNone。sizemethod returnsitemsThe length of the list, that is, the number of elements in the queue.
Output result:
Example
Example usage
q
=
Queue
(
)
q.
enqueue
(
1
)
q.
enqueue
(
2
)
q.
enqueue
(
3
)
(
q.
dequeue
(
)
)
Output: 1
(
q.
size
(
)
)
Output: 2
(
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。
Python3 Examples