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
197 views
in Technique[技术] by (71.8m points)

python; modifying list inside a function

Suppose I have function with list parameter, and inside its body I want to modify passed list, by copying elements of an array to the list:

def function1 (list_arg):
   a = function2()    #function2 returns an array of numbers
   list_arg = list(a)

list1 = [0] * 5
function1(list1)
list1
[0,0,0,0,0]

When doing it like this, it doesn't work. After executing function1(list1), list1 remains unchanged. So, how to make function1 return list1 with the same elements (numbers) as array a?

Question&Answers:os

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

1 Answer

0 votes
by (71.8m points)

If you assign something to the variable list_arg, it will from then on point to the new value. The value it pointed to before that assignment (your original list) will stay unchanged.

If you, instead, assign something to elements of that list, this will change the original list:

list_arg[:] = list(a)

This will make your code work as you wanted it.

But keep in mind that in-place changes are hard to understand and probably can confuse the next developer who has to maintain your code.


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

...