Concept Flow - Peek Top Element of Stack
Start
Check if stack is empty?
Yes→Return None or Error
No
Access top element
Return top element
End
The flow checks if the stack is empty. If not, it accesses and returns the top element without removing it.
stack = [10, 20, 30] top = stack[-1] print(top)
| Step | Operation | Stack State | Pointer Changes | Visual State |
|---|---|---|---|---|
| 1 | Start with stack = [10, 20, 30] | [10, 20, 30] | top pointer not set | 10 -> 20 -> 30 (top) |
| 2 | Check if stack is empty | [10, 20, 30] | No change | 10 -> 20 -> 30 (top) |
| 3 | Access top element stack[-1] | [10, 20, 30] | top pointer points to 30 | 10 -> 20 -> 30 (top) |
| 4 | Return top element 30 | [10, 20, 30] | top pointer unchanged | 10 -> 20 -> 30 (top) |
| 5 | Print top element | [10, 20, 30] | No change | 10 -> 20 -> 30 (top) |
| 6 | End | [10, 20, 30] | No change | 10 -> 20 -> 30 (top) |
| Variable | Start | After Step 3 | Final |
|---|---|---|---|
| stack | [10, 20, 30] | [10, 20, 30] | [10, 20, 30] |
| top | undefined | 30 | 30 |
Peek Top Element of Stack: - Check if stack is empty first - Access top element without removing - Return the top element - Stack remains unchanged - Commonly use stack[-1] in Python
peek operation do in a stack?stack?stack[-1] accesses the last element.stack.pop() removes the element, so it is not peek. stack.peek() and stack.top() are not valid list methods.stack = [10, 20, 30] print(stack[-1]) stack.append(40) print(stack[-1])
stack[-1] is 30, so first print outputs 30.stack[-1] is now 40, so second print outputs 40.stack = [5, 15, 25] top = stack.pop[-1] print(top)
pop is a method and should be called with parentheses, not square brackets. stack.pop[-1] is invalid syntax.stack[-1]. To pop, use stack.pop(). Mixing them causes error.stack[-1] when stack is empty causes IndexError.Pass the test and this pattern moves unknown