Changing one list unexpectedly changes another, too [duplicate]

I have a list of the form

v = [0,0,0,0,0,0,0,0,0]

Somewhere in the code I do

vec=v
vec[5]=5

and this changes both v and vec:

>>> print vec
[0, 0, 0, 0, 0, 5, 0, 0, 0]
>>> print v
[0, 0, 0, 0, 0, 5, 0, 0, 0]

Why does v change at all?


Solution 1:

Why does v change at all?

vec and v are both references.

When coding vec = v you assign v address to vec. Therefore changing data in v will also "change" vec.

If you want to have two different arrays use:

vec = list(v)

Solution 2:

Because v is pointed to the same list as vec is in memory.

If you do not want to have that you have to make a

from copy import deepcopy
vec = deepcopy(v)

or

vec = v[:]