What happens if the peek method is called on an empty Stack?


#1

Question

In this exercise, the peek() method will return the value of get_value() for the top_item. What happens if the Stack is empty when peek() is called?

Answer

At this particular stage of the Stack class implementation, calling peek() on an empty stack will result in a Python error message: AttributeError: 'NoneType' object has no attribute 'get_value'. Ideally, the peek() method should have a check to ensure that the Stack is not empty before attempting the reference the value of self.top_item. Later iterations of the Stack class in this lesson will implement a check.