input1 :
for i in range(5):
lst = [0,0,0,0,0]
lst[i] = 1
print(lst)
output1 :
1, 0, 0, 0, 0
0, 1, 0, 0, 0
0, 0, 1, 0, 0
0, 0, 0, 1, 0
0, 0, 0, 0, 1
input2 :
mainlst = [0,0,0,0,0]
for i in range(5):
templst = mainlst
templst[i] = 1
print(templst)
output2 :
1, 0, 0, 0, 0
1, 1, 0, 0, 0
1, 1, 1, 0, 0
1, 1, 1, 1, 0
1, 1, 1, 1, 1
Why does assigning a value, to a variable, 1) as a list, and 2) as a variable(whose value is the same as the list), not have the same output
i expected the two to give the same output
>Solution :
In the second example you’re referencing the mainlst every time. If you change your code to:
mainlst = [0,0,0,0,0]
for i in range(5):
templst = mainlst.copy()
templst[i] = 1
print(templst)
You’ll get the same results. Look up more about python arrays and deep vs shallow copies.
https://realpython.com/copying-python-objects/