Imagine a pile of dishes: you can look at the top dish without lifting it away. A stack's peek operation returns its top element while leaving the stack unchanged. section 8.19
A reliable peek implementation handles several practical concerns:
- Check whether the stack is empty before accessing its top; otherwise, raise an error for an invalid operation. section 8.12
- Avoid reaching directly into a linked list's private _head attribute; expose a suitable public accessor such as get(i). section 8.12
- Consider whether returning the stored object exposes mutable stack data to outside changes; copying can prevent that, depending on the accessor design. section 8.12
A defensive linked-list peek
A basic implementation checks for emptiness and returns a copied top value. Later, a public linked-list accessor can remove the direct _head access. section 8.12
import copy
def peek(self):
if self.is_empty():
raise ValueError("Cannot peek at an empty stack")
return copy.deepcopy(self._data._head.data())
View the compact Python implementation that raises on an empty stack and deep-copies the top value. section 8.12
Peek is read-only: unlike pop, it does not remove an element. It is optional in some stack interfaces, but useful when a caller needs to inspect the next value before deciding what to do. section 8.9 section 8.19


