-3

As I don't know what title should be given to my this confusion so I'm putting it just a doubt

a = [1,2,3,4,5]
b = a 

for i in range(len(a)):
    c = (i - 4)
    print(a)
    print(b)
    b[c] = a[i]
    print(a)
    print(b)

output

[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[1, 1, 3, 4, 5]
[1, 1, 3, 4, 5]
[1, 1, 3, 4, 5]
[1, 1, 3, 4, 5]
[1, 1, 1, 4, 5]
[1, 1, 1, 4, 5]
...

why values of list a is getting in each step of loop?

galmeriol
  • 461
  • 4
  • 14

1 Answers1

3

Your problem lies in this line:

b = a 

This doesn't do what you think it does. In particular, it does not make a copy of a. After the assignment, both b and a refer to the same object. Thus, any change to b is reflected in a also.

One way to force a shall copy is to use the slice syntax:

b = a[:]
Robᵩ
  • 163,533
  • 20
  • 239
  • 308