We will cover the following in this article
- What is a Stack – a short introduction
- How to implement a Stack in Python
- Investigate the run-time performance
What is a Stack
A Stack is a useful concept that is used in daily life, and hence, a concept that is important to understand and master as a programmer.
To understand Stacks just think of a stack of plates. There are two main operations you can do. First, you can add a plate on top of the stack. That operation is called push adds the element on top of the stack. Second, you can remove the top plate of the stack. That operation is called pop, and returns the top element of the stack.
In the diagram below a Stack is pictured. It contains of a Stack of element on the left side. The operation push of the element 03 is executed and results is pictured on the right side. Notice, that the push operation puts the element on top of the stack.
Below the operation pop is executed. Notice, that the pop operation takes from the top of the stack.
Implementation of a Stack in Python
It is a good idea to have a helper class Node that represents the elements on the stack.
class Node: def __init__(self, element=None, next_node=None): self.element = element self.next_node = next_node
The actual functionality of the Stack is kept in a Stack class.
class Stack: def __init__(self): self.stack = None def push(self, element): self.stack = Node(element, self.stack) def pop(self): element = self.stack.element self.stack = self.stack.next_node return element def is_empty(self): return self.stack is None
Now you can use your stack. Like the example below.
s = Stack() for i in range(5): s.push(i) while not s.is_empty(): print(s.pop())
Will give the following output.
4 3 2 1 0
Notice the order of the element being removed from the stack by pop.
If we look at how the stack perform in order of the data size. To investigate the run-time performance the cProfile library is a good choice and simple to use. The following piece of code will help you investigate the performance.
import cProfile def profile_stack(n): s = Stack() for i in range(n): s.push(i) while not s.is_empty(): s.pop() cProfile.run("profile_stack(100000)")
See the following graph.
As you see, the push and pop operations are constant, O(1), resulting in a linear performance of n push and pop operations as in the above experiment.