Bird
Raised Fist0
DSA Pythonprogramming

Peek Top Element of Stack in DSA Python

Choose your learning style10 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.

Practice

(1/5)
1. What does the peek operation do in a stack?
easy
A. Returns the bottom element of the stack
B. Removes the top element from the stack
C. Adds a new element to the top of the stack
D. Returns the top element without removing it

Solution

  1. Step 1: Understand stack operations

    A stack follows Last-In-First-Out (LIFO). The top element is the last added item.
  2. Step 2: Define peek operation

    Peek returns the top element without removing it, unlike pop which removes it.
  3. Final Answer:

    Returns the top element without removing it -> Option D
  4. Quick Check:

    Peek = top element without removal [OK]
Hint: Peek shows top without removing it [OK]
Common Mistakes:
  • Confusing peek with pop
  • Thinking peek adds elements
  • Assuming peek returns bottom element
2. Which of the following is the correct syntax to peek the top element from a stack implemented as a Python list named stack?
easy
A. stack[-1]
B. stack.peek()
C. stack.top()
D. stack.pop()

Solution

  1. Step 1: Recall Python list indexing

    Python lists use negative indexing; stack[-1] accesses the last element.
  2. Step 2: Differentiate peek from pop

    stack.pop() removes the element, so it is not peek. stack.peek() and stack.top() are not valid list methods.
  3. Final Answer:

    stack[-1] -> Option A
  4. Quick Check:

    Peek = stack[-1] [OK]
Hint: Use stack[-1] to peek top element in Python list [OK]
Common Mistakes:
  • Using pop() which removes element
  • Using non-existent peek() or top() methods
  • Using positive index 0 instead of -1
3. What will be the output of this code?
stack = [10, 20, 30]
print(stack[-1])
stack.append(40)
print(stack[-1])
medium
A. 30\n40
B. 10\n40
C. 30\n30
D. 40\n40

Solution

  1. Step 1: Check initial peek

    Initial stack is [10, 20, 30]. stack[-1] is 30, so first print outputs 30.
  2. Step 2: Append and peek again

    After appending 40, stack becomes [10, 20, 30, 40]. stack[-1] is now 40, so second print outputs 40.
  3. Final Answer:

    30 40 -> Option A
  4. Quick Check:

    Peek before append = 30, after append = 40 [OK]
Hint: Peek shows last element; append adds new last element [OK]
Common Mistakes:
  • Confusing peek with pop output
  • Not updating peek after append
  • Printing first element instead of last
4. Find the error in this code that tries to peek the top element of a stack implemented as a list:
stack = [5, 15, 25]
top = stack.pop[-1]
print(top)
medium
A. pop removes element, so peek is wrong
B. pop is used incorrectly with square brackets
C. stack is empty, so error occurs
D. print statement syntax is wrong

Solution

  1. Step 1: Analyze pop usage

    pop is a method and should be called with parentheses, not square brackets. stack.pop[-1] is invalid syntax.
  2. Step 2: Understand correct peek syntax

    To peek, use stack[-1]. To pop, use stack.pop(). Mixing them causes error.
  3. Final Answer:

    pop is used incorrectly with square brackets -> Option B
  4. Quick Check:

    pop() needs parentheses, not brackets [OK]
Hint: Use parentheses for pop(), brackets for indexing [OK]
Common Mistakes:
  • Using pop with brackets instead of parentheses
  • Confusing peek with pop
  • Assuming pop[-1] is valid syntax
5. Given a stack implemented as a list, how can you safely peek the top element without causing an error if the stack is empty?
hard
A. Use stack.pop() and catch exceptions
B. Use stack[-1] directly without checks
C. Check if stack is not empty before peeking
D. Assign None to top element always

Solution

  1. Step 1: Understand empty stack risk

    Accessing stack[-1] when stack is empty causes IndexError.
  2. Step 2: Implement safe peek

    Check if stack length > 0 before peeking to avoid error.
  3. Final Answer:

    Check if stack is not empty before peeking -> Option C
  4. Quick Check:

    Peek safely by checking stack length first [OK]
Hint: Always check stack not empty before peek [OK]
Common Mistakes:
  • Peeking without checking empty stack
  • Using pop() which removes element
  • Ignoring exceptions from empty stack access
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard