Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying list in python: deep vs shallow copy: gotcha for me in python?

Tags:

python

So this is what I tried to do.

vectorized = [0] * length
for i,key in enumerate(foo_dict.keys()):
    vector = vectorized
    vector[i] = 1
    print vector
    vector = vectorized
print vectorized

So what I was hoping was for example the length is 4. So i create a 4 dimension vector:

  vectorized=[0,0,0,0]

now, depending on the index of dictionary (which is also of length 4 in this case) create a vector with value 1 while rest has zero

so vector = [1, 0,0,0]  , [0,1,0,0] and so on..

Now instead what is happening is:

 vector = [1,0,0,0],[1,1,0,0] .. and finally [1,1,1,1]

even vectorized is now

   [1,1,1,1]

Whats wrong I am doing. and how do i achieve what i want to achieve. Basically I am trying to create unit vectors. Thanks

like image 217
frazman Avatar asked Mar 30 '12 00:03

frazman


2 Answers

This line (these lines, really):

vector = vectorized

copies the list reference. You need to do a shallow copy of the sequence contents.

vector = vectorized[:]
like image 84
Ignacio Vazquez-Abrams Avatar answered Nov 14 '22 23:11

Ignacio Vazquez-Abrams


You are creating a single list and then giving it several different names. Remember that a = b doesn't create a new object. It just means that a and b are both names for the same thing.

Try this instead:

for ...:
    vector = [0] * length
    ...
like image 33
Mark Byers Avatar answered Nov 14 '22 21:11

Mark Byers