Question: Implement peek(stack) that returns, but doesn't remove, the top element from a stack. Return None if list is empty.
I tried many times but did not successfully get it, anyone can help?
My attempt:
def peek_stack(stack): if stack == []: return None else: s= stack.copy() return s.pop(0) 53 Answers
If you need to use your way to solve this, please use return s.pop() rather than return s.pop(0), because s.pop() will pop up the last element, but s.pop(0) will pop up the first element...
And by the way, it's recommend just implement it like this(it can avoid copy your stack, and improve performance)
def peek_stack(stack): if stack: return stack[-1] # this will get the last element of stack else: return None 0Simpler one:
def peek_stack(stack): if stack: return stack[-1] 1def peek(stk): if stk == []: return None else: top = len(stk) - 1 return stk[top] 5