0
def push(stack:list):
    stack = stack + [2]

stack = []
print(stack)
stack = stack + [1]
print(stack)
push(stack)
print(stack)

This is my python code.

I expected the final value of the list to be [1,2], but the result was [1]. I understand that the stack variable in the stack = stack + [2] code in push() is used as a local variable, but I don't know why. Also, I would like to know how to write the code, and how to add elements to a list without using append() inside a function that receives a list as a parameter.

  • Can you using extend – XMehdi01 May 07 '23 at 17:56
  • 1
    Inside of `push`, `stack` is effectively a *local* variable, so assignments to it do not effect the global `stack`. See what happens if you change the name of the parameter. – Scott Hunter May 07 '23 at 17:56
  • 1
    Why can't you use `append`? – Scott Hunter May 07 '23 at 17:57
  • 1
    You are also creating new list each time when doing `stack = stack + [2]`. – sudden_appearance May 07 '23 at 17:58
  • `stack = stack + [2]` makes a **new** list object (containing the contents of the existing list object, and 2), and assigns that object to the local name `stack` within the function. The global name `stack` still refers to the pre-existing list object, which has not changed. To change that existing object, `stack.append(2)`, or `stack.extend([2])`, or `stack += [2]`. – slothrop May 07 '23 at 18:00
  • See: https://stackoverflow.com/questions/575196/why-can-a-function-modify-some-arguments-as-perceived-by-the-caller-but-not-oth – slothrop May 07 '23 at 18:01

0 Answers0