1
def push(item,stack=[]):
        #print('stack',stack)
        stack.append(item)
        return stack


if __name__== '__main__':
    print(push(5))
    print(push(6))
    print(push(7))
    stck = push(58)
    print(stck.pop())
    print(stck.pop())
    print(push(9))




Answer:
[5]
[5, 6]
[5, 6, 7]
58
7
[5, 6, 9]

How the second push(6) is maintaining the stack array isnt the second push() method supposed to create a new array, and how its maintaining the array between the multiple method calls of push()

  • Does this answer your question? ["Least Astonishment" and the Mutable Default Argument](https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument) – bruno desthuilliers Apr 28 '20 at 07:42

1 Answers1

0
Answer:
[5] -> You use *stack = []* variable from the push() function as location to store
[5, 6] -> Same
[5, 6, 7] -> Same
58 -> It creates inside new variable *stck* a copy for the *stack = []* variable 
7 -> It removes from the *stack = []*
[5, 6, 9] -> It addes to the *stack = []* the new element

The *stck* variable is just a reference to the *stack* variable, changing that one, it changes the stck as well.
Is not recommended to use a list as a function parameter.

Full article here: https://runestone.academy/runestone/books/published/thinkcspy/Lists/UsingListsasParameters.html

  • Got it, along with this, i also understood that the function in python is a first class object and hence when the def push is executed for first time the array stack is allocated and maintained in the scope of that function and subsequent calling of that function will be using that same array in the scope of that function this applies to the optional parameter if its non-primitive,same behavior isn't observed for primitive understandably. – rengasamy venkittaraman Apr 29 '20 at 05:00