0

Here I have a vector a=[1,2,3,4,5]

a=b
a[0]=a[2]
print a
a=[2,2,3,4,5]
b=[2,2,3,4,5]

but I don't want vector b to be changed, I want it always b=[1,2,3,4,5]

Actually, you can regard b as the original vector of a.

陳俊良
  • 319
  • 1
  • 6
  • 13

1 Answers1

1

Use copy funtion like this :

    a=b.copy()
    a[0]=a[2]
    print a
    a=[3,2,3,4,5]
    b=[2,2,3,4,5]

for a list, a = b just copies the reference. So when you change one value of the list then the value of all variables (those hold the same reference) become changed. copy() or deepcopy() function actually copies the list. You can read this doc.

Update with your input :

b=[1,2,3,4,5]
a=b.copy()
a[0]=a[2]
print(a)
print(b)

It prints :

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

Using list slicing in this case is weird but working one :

b=[1,2,3,4,5]
a=b[:]
a[0]=a[2]
print(a)
print(b)
Taohidul Islam
  • 5,246
  • 3
  • 26
  • 39