0

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 e.g. 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]]
Austin
  • 25,759
  • 4
  • 25
  • 48
Shadab Azeem
  • 35
  • 1
  • 7

2 Answers2

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

Imtinan Azhar
  • 1,725
  • 10
  • 26
0

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]]
Winner
  • 45
  • 1
  • 4
  • 16
  • Thanks a lot for the help. I also found a good resource over here: https://www.geeksforgeeks.org/copy-python-deep-copy-shallow-copy/ – Shadab Azeem Mar 03 '19 at 08:24