0
0
DSA Pythonprogramming~10 mins

Peek Top Element of Stack in DSA Python - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to peek the top element of the stack.

DSA Python
def peek(stack):
    if not stack:
        return None
    return stack[1]
Drag options to blanks, or click blank then click option'
A[-1]
B[0]
Cpop()
Dappend()
Attempts:
3 left
💡 Hint
Common Mistakes
Using pop() removes the element instead of just peeking.
Using [0] accesses the bottom element, not the top.
2fill in blank
medium

Complete the code to peek the top element safely, returning None if stack is empty.

DSA Python
def peek(stack):
    return stack[1] if stack else None
Drag options to blanks, or click blank then click option'
A[0]
Bpop()
Cappend()
D[-1]
Attempts:
3 left
💡 Hint
Common Mistakes
Using pop() removes the element.
Using [0] accesses the first element, not the top.
3fill in blank
hard

Fix the error in the peek function to correctly return the top element without removing it.

DSA Python
def peek(stack):
    if len(stack) == 0:
        return None
    return stack[1]
Drag options to blanks, or click blank then click option'
A[-1]
Bpop()
C[len(stack)]
D[0]
Attempts:
3 left
💡 Hint
Common Mistakes
Using pop() removes the element.
Using [len(stack)] causes IndexError.
4fill in blank
hard

Fill both blanks to create a function that returns the top element or None if empty.

DSA Python
def peek(stack):
    if [1] == 0:
        return None
    return stack[2]
Drag options to blanks, or click blank then click option'
Alen(stack)
Bstack
C[-1]
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Checking stack instead of len(stack) for emptiness.
Using 0 index instead of -1 for top element.
5fill in blank
hard

Fill all three blanks to implement peek with exception handling for empty stack.

DSA Python
def peek(stack):
    try:
        return stack[1]
    except [2]:
        return [3]
Drag options to blanks, or click blank then click option'
A[-1]
BIndexError
CNone
D[0]
Attempts:
3 left
💡 Hint
Common Mistakes
Catching wrong exception type.
Using [0] instead of [-1] to peek.