Search code examples
pythonpython-3.xlistassignment-operator

How does array assignment work within a python function?


I'm confused by the following example. Let a=[1] be a python list and try to write a function which re-assigns the list such that we will have a=[2] after running the function.

A simple function which works is

def works1(arr):
    arr[0]=2

or another example is

def works2(arr):
    arr[0]=2*arr[0]

Either does what I would want when running works1(a) or works2(a): both set a=[2].

However, something like the following which tries to re-assign the entire array at once, rather than doing it component-by-component, will fail.

def fails1(arr):
    arr=[2*x for x in arr]

Running fails1(a) does not reassign a, which is still given by a=[1].

Could someone please explain this behavior or point me to where in the documentation I should be looking to understand the above?

Edit: For context, if helpful, I was trying to understand why the mergeSort code at this site was able to re-assign an externally defined list. Initially thought that alist within that mergeSort code should be a local variable.


Solution

  • arr is a reference to a list object

    When you write arr[0]=1 you change the element in this referenced object. But when you write arr=[..new list..] you just make arr refer to a new object, and it does not affect previous object.