liveBook · Manning

Peek

As explained in Grokking Data Structures

A peek operation returns the top element of a stack without removing it or changing the stack's structure.

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

How Grokking Data Structures covers it

How deep it goes
Explains empty checks, private-attribute access, mutable results, copying, and public accessors, then assigns implementation exercises.
Examples
Uses a pile-of-dishes analogy, Python linked-list code, deepcopy, get(i), and exercises comparing linked-list and dynamic-array stacks.
What it assumes
Assumes basic Python classes and linked lists while teaching stack behavior, edge cases, and encapsulation through implementation.
What you can do after
Build it from scratch by implementing peek, handling empty stacks, protecting mutable values, and replacing private access with get(i).
How it connects
Connects peek to stacks, pop, linked lists, dynamic arrays, queues, and data encapsulation.

Also explained in

Compare how 3 books explain peek →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Grokking Data Structures. The section links point to the parts of the book it draws on.