October 2018
Beginner to intermediate
398 pages
11h 1m
English
There is another important operation that can be applied on stacks—the peek method. This method returns the top element from the stack without deleting it from the stack. The only difference between peek and pop is that the peek method just returns the topmost element; however, in the case of a pop method, the topmost element is returned and also that element is deleted from the stack.
The pop operation allows us to look at the top element without changing the stack. This operation is very straightforward. If there is a top element, return its data; otherwise, return None (thus, the behavior of peek matches that of pop):
def peek(self): if self.top return self.top.data else: return None
Read now
Unlock full access