This question already has an answer here:
- How to clone or copy a list? 19 answers
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?
vec and v are both pointers. 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:
you could use
"Alex Martelli's opinion (at least back in 2007) about this is, that it is a weird syntax and it does not make sense to use it ever. ;) (In his opinion, the next one is more readable)."
I mean it was Erez's link... "How to clone or copy a list in Python?"
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
or
In order to save on memory, vec will be pointed to the same array unless you specifically say otherwise.
copy arrays like this
vec=v[:]
The ability to point to an array instead of copying it is useful when passing data from function to function. If you had this function
And you wanted to do something with someBigArray
You don't want to have to waste time waiting for the program to copy all of the data in someBigArray to arr, so instead the default behaviour is to give arr a pointer to someBigArray.
A similar question was asked How to clone or copy a list?
Run this code and you will understand why variable v changes.
This code prints the following output on my interpreter:
As you can see, lists a and b point to the same memory location. Whereas, list c is a different memory location altogether. You can say that variables a and b are alias for the same list. Thus, any change done to either variable a or b will be reflected in the other list as well, but not on list c Hope this helps! :)