6

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

1
  • I wish more question were this quality. +1. I would only recommend improving the title. Commented Mar 30, 2012 at 0:57

5 Answers 5

9

This line (these lines, really):

vector = vectorized

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

vector = vectorized[:]
Sign up to request clarification or add additional context in comments.

Comments

5

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

Comments

4

The line

vector = vectorized

is not making a copy of vectorized. Any time you change vector from then on, you are also changing `vectorized.

You can change the first line to:

vector = vectorized[:]

or

import copy
vector = copy.copy(vectorized)

If you want to make a copy.

Comments

2

While in Python, when you assign a list to a new list, the new list is just a pointer rather than a brand new one.

So when you trying to modify the value of "vector", you are actually changing the value of "vectorized". And in your case, vector[i] = 1 is same as vectorized[i] = 1

Comments

1

Your problem is that when you write vector = vectorized it is not creating a copy of the array, rather it is creating a binding between the two.

Assignment statements in Python do not copy objects, they create bindings between a target and an object.

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

This should help you get it sorted out.

And here's a little 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: Jeez you guys are fast!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.