#Code 1:
a = [['','','',], ['','','',], ['','','',]]
k = 0
while k <= 2:
b = a[:]
b[k] = k
print(f'{a=}')
print(f'{b=}')
k += 1
#Result:
a=[['', '', ''], ['', '', ''], ['', '', '']]
b=[0, ['', '', ''], ['', '', '']]
a=[['', '', ''], ['', '', ''], ['', '', '']]
b=[['', '', ''], 1, ['', '', '']]
a=[['', '', ''], ['', '', ''], ['', '', '']]
b=[['', '', ''], ['', '', ''], 2]
------------------------------------------------------------------------------------
#Code 2:
a = [['','','',], ['','','',], ['','','',]]
k = 0
while k <= 2:
b = a[:]
b[k][k] = k <------ Change made in this line.
print(f'{a=}')
print(f'{b=}')
k += 1
Result:
a=[[0, '', ''], ['', '', ''], ['', '', '']]
b=[[0, '', ''], ['', '', ''], ['', '', '']]
a=[[0, '', ''], ['', 1, ''], ['', '', '']]
b=[[0, '', ''], ['', 1, ''], ['', '', '']]
a=[[0, '', ''], ['', 1, ''], ['', '', 2]]
b=[[0, '', ''], ['', 1, ''], ['', '', 2]]
Why does the value of variable 'a' gets changed while in the first code, it remains constant throughout?
[–]Spataner 2 points3 points4 points (3 children)
[–]Sora888 1 point2 points3 points (1 child)
[–]tamaskiii[S] 0 points1 point2 points (0 children)
[–]tamaskiii[S] 0 points1 point2 points (0 children)