Learn how you can become a Python programmer in just 12 weeks.

    We respect your privacy. Unsubscribe at anytime.

    How to Implement a Stack in Python and Check the Run-time Performance

    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.

    Run-time Performance

    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.

    Python for Finance: Unlock Financial Freedom and Build Your Dream Life

    Discover the key to financial freedom and secure your dream life with Python for Finance!

    Say goodbye to financial anxiety and embrace a future filled with confidence and success. If you’re tired of struggling to pay bills and longing for a life of leisure, it’s time to take action.

    Imagine breaking free from that dead-end job and opening doors to endless opportunities. With Python for Finance, you can acquire the invaluable skill of financial analysis that will revolutionize your life.

    Make informed investment decisions, unlock the secrets of business financial performance, and maximize your money like never before. Gain the knowledge sought after by companies worldwide and become an indispensable asset in today’s competitive market.

    Don’t let your dreams slip away. Master Python for Finance and pave your way to a profitable and fulfilling career. Start building the future you deserve today!

    Python for Finance a 21 hours course that teaches investing with Python.

    Learn pandas, NumPy, Matplotlib for Financial Analysis & learn how to Automate Value Investing.

    “Excellent course for anyone trying to learn coding and investing.” – Lorenzo B.

    Leave a Comment