Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
131 views
in Technique[技术] by (71.8m points)

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.

question from:https://stackoverflow.com/questions/66052555/how-does-array-assignment-work-within-a-python-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...