0
0
DSA Pythonprogramming

Peek Top Element of Stack in DSA Python

Choose your learning style9 modes available
Mental Model
A stack is like a pile of plates where you only see and use the top plate. Peeking means looking at the top plate without removing it.
Analogy: Imagine a stack of books on a table. You can only see and pick the top book. Peeking is just looking at the title of the top book without taking it off.
Top -> [ 3 ] -> [ 2 ] -> [ 1 ] -> null
          ↑
Dry Run Walkthrough
Input: stack: push 1, push 2, push 3; peek top element
Goal: To see the top element of the stack without removing it
Step 1: push 1 onto stack
Top -> [ 1 ] -> null
          ↑
Why: We start with an empty stack and add the first element
Step 2: push 2 onto stack
Top -> [ 2 ] -> [ 1 ] -> null
          ↑
Why: New element goes on top, pushing previous down
Step 3: push 3 onto stack
Top -> [ 3 ] -> [ 2 ] -> [ 1 ] -> null
          ↑
Why: Add another element on top, stack grows upwards
Step 4: peek top element
Top -> [ 3 ] -> [ 2 ] -> [ 1 ] -> null
          ↑
Why: Look at the top element without removing it
Result:
Top -> [ 3 ] -> [ 2 ] -> [ 1 ] -> null
Peeked element: 3
Annotated Code
DSA Python
class Stack:
    def __init__(self):
        self.items = []

    def push(self, item):
        self.items.append(item)  # add item on top

    def peek(self):
        if not self.items:
            return None  # empty stack check
        return self.items[-1]  # return top item without removing

# Driver code
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
peeked = stack.peek()
print('Stack:', ' -> '.join(map(str, reversed(stack.items))) + ' -> null')
print('Peeked element:', peeked)
self.items.append(item) # add item on top
push new element on top of stack
if not self.items: return None # empty stack check
check if stack is empty before peeking
return self.items[-1] # return top item without removing
return the last element which is the top of stack
OutputSuccess
Stack: 3 -> 2 -> 1 -> null Peeked element: 3
Complexity Analysis
Time: O(1) because peek just accesses the last element directly
Space: O(n) because stack stores n elements
vs Alternative: Compared to popping, peek does not remove elements so it is faster and safer when you only want to see the top
Edge Cases
empty stack
peek returns None indicating no elements
DSA Python
if not self.items:
    return None  # empty stack check
When to Use This Pattern
When you need to see the last added item without changing the stack, use peek to quickly access the top element.
Common Mistakes
Mistake: Trying to peek by popping which removes the element
Fix: Use indexing to access the last element without removing it
Summary
Peek returns the top element of the stack without removing it.
Use peek when you want to check the top item but keep the stack unchanged.
The key is to access the last element directly without modifying the stack.