Implement a Simple Stack Class in Python
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:
push(item): Push the elementitemonto the top of the stack.pop(): Remove and return the top element of the stack.peek(): Return the top element without removing it.is_empty(): Check whether the stack is empty.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:
__init__(self): Initialize an empty listitemsto store the elements of the stack.is_empty(self): Check whether the stack is empty; if theitemslist is empty it returnsTrue; otherwise, returnsFalse。push(self, item): Push the elementitemtoitemslist, that is, push onto the top of the stack.pop(self): Remove and return theitemslast element of the list, that is, the top element of the stack. If the stack is empty, raiseIndexErrorexception.peek(self): Returns the number ofitemsthe last element of the list, that is, the top element of the stack, without removing it. If the stack is empty, raiseIndexErrorexception.size(self): Returns the number ofitemsThe 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
)
(
stack.
peek
(
)
)
Output: 3
(
stack.
pop
(
)
)
Output: 3
(
stack.
size
(
)
)
Output: 2
(
stack.
is_empty
(
)
)
Output: False
stack.
pop
(
)
stack.
pop
(
)
(
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.
Python3 Examples