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

Implement a Simple Stack Class in Python

Implement a Simple Stack Class in Python

Document Object Reference Manual Python3 Examples

A stack is a data structure that follows the last-in-first-out (LIFO) principle. We can use a Python list to implement a simple stack class with the following basic operations:

  1. push(item): Push the element item onto the top of the stack.
  2. pop(): Remove and return the top element of the stack.
  3. peek(): Return the top element without removing it.
  4. is_empty(): Check whether the stack is empty.
  5. size(): Return the number of elements in the stack.

Example

class

Stack:

   

def

init

(

self

)

:

       

self

.

items

=

[

]

   

def

is_empty

(

self

)

:

       

return

self

.

items

==

[

]

   

def

push

(

self

,

item

)

:

       

self

.

items

.

append

(

item

)

   

def

pop

(

self

)

:

       

if

self

.

is_empty

(

)

:

           

raise

IndexError

(

"pop from empty stack"

)

       

return

self

.

items

.

pop

(

)

   

def

peek

(

self

)

:

       

if

self

.

is_empty

(

)

:

           

raise

IndexError

(

"peek from empty stack"

)

       

return

self

.

items

[

1

]

   

def

size

(

self

)

:

       

return

len

(

self

.

items

)

Code analysis:

  1. __init__(self): Initialize an empty list items to store the elements of the stack.
  2. is_empty(self): Check whether the stack is empty; if the items list is empty it returns True; otherwise, returns False。
  3. push(self, item): Push the element item to items list, that is, push onto the top of the stack.
  4. pop(self): Remove and return the items last element of the list, that is, the top element of the stack. If the stack is empty, raise IndexError exception.
  5. peek(self): Returns the number of items the last element of the list, that is, the top element of the stack, without removing it. If the stack is empty, raise IndexError exception.
  6. size(self): Returns the number of items The length of the list, that is, the number of elements in the stack.

Output result:

Example

Example usage

stack

=

Stack

(

)

stack.

push

(

1

)

stack.

push

(

2

)

stack.

push

(

3

)

print

(

stack.

peek

(

)

)

 

Output: 3

print

(

stack.

pop

(

)

)

 

Output: 3

print

(

stack.

size

(

)

)

 

Output: 2

print

(

stack.

is_empty

(

)

)

 

Output: False

stack.

pop

(

)

stack.

pop

(

)

print

(

stack.

is_empty

(

)

)

 

Output: True

In this example we first create a stack object stack, then add the elements 1、2 and 3 onto the stack. Then we look at the top element (3), and remove it. Finally we check the stack size and whether it is empty.

Document Object Reference Manual Python3 Examples