Changing one list unexpectedly changes another, to

2019-01-05 06:05发布

This question already has an answer here:

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?

5条回答
Melony?
2楼-- · 2019-01-05 06:35

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:

vec = list(v)
查看更多
三岁会撩人
3楼-- · 2019-01-05 06:37

you could use

vec=v[:] #but

"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)."

vec=list(v)

I mean it was Erez's link... "How to clone or copy a list in Python?"

查看更多
对你真心纯属浪费
4楼-- · 2019-01-05 06:38

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[:]
查看更多
欢心
5楼-- · 2019-01-05 06:50

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

def foo():
  return someBigArray

And you wanted to do something with someBigArray

def bar():
  arr = foo()
  processArray(arr)

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?

查看更多
放我归山
6楼-- · 2019-01-05 06:52

Run this code and you will understand why variable v changes.

a = [7, 3, 4]
b = a
c = a[:]
b[0] = 10
print 'a: ', a, id(a)
print 'b: ', b, id(b)
print 'c: ', c, id(c)

This code prints the following output on my interpreter:

a:  [10, 3, 4] 140619073542552                                                                                                
b:  [10, 3, 4] 140619073542552                                                                                                
c:  [7, 3, 4] 140619073604136

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! :)

查看更多
登录 后发表回答