d = [1,2,3,4,5,6]
for i in range(3):
d1 = d
d1[i] = 10
print(d1)
print(d)
‘’‘I am getting output as’’’
[10, 10, 10, 4, 5, 6]
[10, 10, 10, 4, 5, 6]
‘’‘I am confused, why the values of d has changed and what is the solution for this ‘’’
d = [1,2,3,4,5,6]
for i in range(3):
d1 = d
d1[i] = 10
print(d1)
print(d)
‘’‘I am getting output as’’’
[10, 10, 10, 4, 5, 6]
[10, 10, 10, 4, 5, 6]
‘’‘I am confused, why the values of d has changed and what is the solution for this ‘’’
Lists in python are mutable objects
So when you wrote
d1 = d
both the variables were referring to the same memory address !
use this to avoid such scenarios
d1 = d.copy()