In this code, I was expecting that list A
will have the same value even if I assign it to another temp
variable and then print the argument A
using the function foo
. However, if A was a scalar eg A=3
then the value of A
remains the same even after calling foo
.
Where am I going wrong? Is there a problem in the scope of variables? I found some related Strange behavior of lists in python answer but couldn't figure out a fix for my problem.
A = [ [ 0 for i in range(3) ] for j in range(3) ]
def foo(input):
temp= input
temp[0][0]=12
print(input)
print(A)
answer = foo(A)
Output:
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
[[12, 0, 0], [0, 0, 0], [0, 0, 0]]
instead of input, use the .copy
this will make a copy of the array and assign new addresses to temp, what you do is shallow copying, where temp = input, just copies the address of the input array to temp, rather than making a copy of the list.
So you may either do foo(A.copy())
or temp=input.copy()
also note input is not a good name since it is already assigned to a python function, use something like foo_arg or something
Please this, I used deepcopy
from copy import copy, deepcopy
A = [ [ 0 for i in range(3) ] for j in range(3) ]
def foo(input):
temp = deepcopy(input)
temp[0][0]=12
return temp
print('origin', A)
answer = foo(A)
print('after', A)
print('result', answer)
Result:
origin [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
after [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
result [[12, 0, 0], [0, 0, 0], [0, 0, 0]]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.