Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing one list unexpectedly changes another, too [duplicate]

Tags:

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?

like image 235
sodiumnitrate Avatar asked Apr 21 '15 23:04

sodiumnitrate


2 Answers

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) 
like image 153
Erez Haim Avatar answered Sep 27 '22 18:09

Erez Haim


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[:] 
like image 40
stackattack Avatar answered Sep 27 '22 18:09

stackattack