0

I'm a newbie with Python, and I really don't understand why occurs this:

vector1 = [1,0,0,1]
left  = vector1
print(str(left))

right = vector1
right[0] = 2

print(str(left))
print(str(right))

The output is:

[1, 0, 0, 1]
[2, 0, 0, 1]
[2, 0, 0, 1]

What I really want is:

[1, 0, 0, 1]
[1, 0, 0, 1]
[2, 0, 0, 1]

Why 'left' vector is updated if I fixed it before with the initial 'vector1' value?

I'm sure that this is a newbie question, but I'm used to code in MatLab and I'm getting confused...

Thanks in advance!

Ander Biguri
  • 35,140
  • 11
  • 74
  • 120
Víctor Martínez
  • 854
  • 2
  • 11
  • 29
  • `left` and `right` are not copies.. – Martijn Pieters Feb 17 '17 at 10:01
  • After `left = vector1`, you have two variables referring to the same list. If you want two lists, you need to copy the list. E.g. `left = list(vector1)`, `right = list(vector1)` . – khelwood Feb 17 '17 at 10:01
  • Check out the execution of your code in this [link](http://www.pythontutor.com/visualize.html#code=vector1%20%3D%20%5B1,0,0,1%5D%0Aleft%20%20%3D%20vector1%0Aprint%28str%28left%29%29%0A%0Aright%20%3D%20vector1%5B%3A%5D%0Aright%5B0%5D%20%3D%202%0A%0Aprint%28str%28left%29%29%0Aprint%28str%28right%29%29&cumulative=false&curInstr=7&heapPrimitives=false&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false). Then try to edit the code to inspect the change. Use `left = vector1[:]` as @Darth suggests. – SSSINISTER Feb 17 '17 at 10:06

1 Answers1

1

when you say

left  = vector1

Python does not copy the contents of list but the new list left now refers to vector1

So when you change the new list, the old list is also changed.

Mithilesh Gupta
  • 2,800
  • 1
  • 17
  • 17