Peek stack in python 3

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

Simpler one:

def peek_stack(stack):
    if stack:
        return stack[-1]

Tags:

Python