2

func_two

def func_two(x):
    x[1][1] = x[2][1]
    x[2][1] = 0 
    return x

a = [[12, 11, 7, 13], [6, 0, 8, 3], [9, 4, 10, 2], [5, 14, 15, 1]]
print(a, ":before function")
b = func_two(a)
print(a, ":after function")
print(b, ":value of b")

output for this is

[[12, 11, 7, 13], [6, 0, 8, 3], [9, 4, 10, 2], [5, 14, 15, 1]] :before function
[[12, 11, 7, 13], [6, 4, 8, 3], [9, 0, 10, 2], [5, 14, 15, 1]] :after function
[[12, 11, 7, 13], [6, 4, 8, 3], [9, 0, 10, 2], [5, 14, 15, 1]] :value of b

why did the value of "a" change after the function? how do I run the func_two without changing the variable outside the function (I haven't declared any variable as a global variable, this shouldn't happen)

code that works correctly func_one

def func_one(x):
    x = [[3]]
    return x 

a = [[5]]
print(a, ":before function")

b = func_one(a)

print(a, ":after function")
print(b, ":value of b")

output for this is

[[5]] :before function
[[5]] :after function
[[3]] :value of b

why is func_one working when func_two is not working ?

AcK
  • 2,063
  • 2
  • 20
  • 27
gokul gupta
  • 330
  • 4
  • 13
  • 2
    You're expecting a lot more implicit copies than Python does. I recommend reading https://nedbatchelder.com/text/names.html - it's a great introduction to how Python variables and objects work. – user2357112 Oct 29 '20 at 10:42
  • thanks, @Wups that does solve my question. – gokul gupta Oct 29 '20 at 10:55
  • 1
    and thanks @Monica, --nedbatchelder.com/text/names.html-- this was a great read, I had no clue python handled variables this way. this actually explains a lot of errors I have had earlier (i had earlier solved them by god know how (doing random things)) not knowing the actual cause of why the problem was happening!!!! thanks a lot – gokul gupta Oct 29 '20 at 10:59

1 Answers1

0

the question has been answered in the comments by @user2357112 supports Monica, and by @Wups

answer

import copy

def transition(x):
    y = copy.deepcopy(x)
    y[1][1] = y[2][1]
    y[2][1] = 0 
    return y

a = [[12, 11, 7, 13], [6, 0, 8, 3], [9, 4, 10, 2], [5, 14, 15, 1]]

print(a, ":before function")

b = transition(a)

print(a, ":after function")
gokul gupta
  • 330
  • 4
  • 13