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.
arris a local variable. When you assign it, it no longer contains a reference to the original list.arr[:] = [2*x for x in arr]a != arr.a[0]just mutates state on an object, completely different from a reassignment that takesaand points it to an entirely different, newly allocated list. The original variable in the calling scope won't be affected by such a reassignment.works1andworks2: the previousainstances should have beenarr's. But @Barmar, yes exactly, I was actually confused why theworks1andworks2functions accomplish what I want at all, since I thought they'd just be assigning values to a local variable. I see now that since I did not actually initialize whatarris in either of these cases, they cannot be making a new local variable namedarr, unlikefails1.arr's where there werea's inworks1andworks2. But I think I understand now: could you tell me if my comment above is correct?