Copy list in python: deep or shallow copy: gotcha for me in python?

So this is what I was trying 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 I was hoping, for example, the length is 4. So I am creating a 4-dimensional vector:

  vectorized=[0,0,0,0] 

Now, depending on the index of the dictionary (which in this case also has a length of 4), create a vector with a value of 1, and the remainder will be zero

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

Now, instead, the following happens:

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

even vectorized now

  [1,1,1,1] 

What am I doing wrong. and how do I achieve what I want to achieve. I am mainly trying to create unit vectors. Thanks

+6
source share
5 answers

This line (these lines, really):

 vector = vectorized 

copies the link to the list. You need to make a shallow copy of the contents of the sequence.

 vector = vectorized[:] 
+9
source

You create one list and then give it several different names. Remember that a = b does not 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 ... 
+5
source

Line

 vector = vectorized 

Don't copy vectorized . Every time you change vector from now on, you also change "vectorized".

You can change the first line to:

 vector = vectorized[:] 

or

 import copy vector = copy.copy(vectorized) 

If you want to make a copy.

+4
source

So far in Python, when you assign a list to a new list, the new list is just a pointer, not a new one.

Therefore, when you try to change the value of "vector", you actually change the value of "vectorized". And in your case, vector[i] = 1 is the same as vectorized[i] = 1

+2
source

Your problem is that when writing vector = vectorized it does not create a copy of the array, but creates a connection between them.

Assignment operators in Python do not copy objects; they create bindings between an object and an object.

http://docs.python.org/library/copy.html

This will help you figure it out.

And here is a small snippet from the Python REPL to show you what I mean.

 >>> vectorized = [0] * 4 >>> print vectorized [0, 0, 0, 0] >>> vector = vectorized >>> vector[1] = 1 >>> print vectorized [0, 1, 0, 0] 

EDIT: Damn guys fast!

+1
source

Source: https://habr.com/ru/post/912001/


All Articles