Hi I have a simple code whose output is not what I expected. The code will change all '1' in an array to '0'. See below:
class Test(object):
def change(self, grid):
print("before change", grid) #output: ["1","1","1","1","0"]
self.change_here(grid)
print('after change',grid) #output: ['0', '0', '0', '0', '0']
def change_here(self, grid):
for i in range(len(grid)):
if grid[i] == '1':
grid[i] = '0'
print("in change here", grid) #output: ['0', '0', '0', '0', '0']
grid=["1","1","1","1","0"]
Test().change(grid)
My question: why the output in print('after change',grid) becomes ['0', '0', '0', '0', '0']? Wasn't it supposed to be ["1","1","1","1","0"], because it was changed in another function as an local variable.
I wrote another sample code, its output is exactly what I expected.
class Test:
def change(self, b):
print('before change', b) #3
self.change_here(b)
print("after change", b) # 3
def change_here(self, b):
b = 4
print('in change here', b)# 4
b = 3
Test().change(b)
Please tell me what happened in the first sample and why. I tested on both python2 and 3 which give me same outputs. Thanks in advance!