# Copy vectors

Hello everyone,

I have the following problem: I have two vectors v = vector(QQ, [1,1]), w = vector(QQ, [3,3]). I want to copy the coefficients of w into v. I can't set v = w directly, beacuse v is used as a value in some dictionaries. I could loop over the list() of the vectors, but I was wondering if there is some better way to copy all of the entries.

Example from comment:

l = {1: v}; v.set(1,2) Now l == {1: (1, 2)}, but v = copy(w) does not change l

edit retag close merge delete

Sort by » oldest newest most voted

Responding to updated issue: To some extent this is a Python issue, even for lists. v = int(22); L= [v]; L; v= int(23); L gives 22 both times. v.set() works because you didn't actually change the reference the variable v has, if I understand correctly.

The following does what you want, and isn't quite the loop you mentioned, though it's close. I don't know if there is a way to avoid the Python thing (feature, really) above.

sage: for x in w.iteritems(): v.set(*x)
....:

more

Assignment by reference is definitely an intentional design decision in python.

Responding to @Mathmon's comment to @kcrisman's first (?) answer: that's because "v" is a reference (pointer) to a vector object somewhere in memory. The statement v = copy(w) creates a new vector in memory with a copy of ws content and then assigns v as a reference to that new vector.

In the dictionary, I is another reference (to the location in memory of the value associated with the key 1. So, for example if you want to update the vector value in I you could do something like:

sage: I = { 1: vector(QQ, (1,2)) }
sage: a = I
sage: a.set(0,3)
sage: I
{1: (3, 2)}


to reassign the reference I use it's name (not a secondary reference to the same location):

sage: w = vector(QQ, (4,5))
sage: I = copy(w)
sage: I
{1: (4, 5)}

more

Do you need this?

sage: v = vector(QQ, [1,1])
sage: w = vector(QQ, [3,3])
sage: v; w
(1, 1)
(3, 3)
sage: v = copy(w)
sage: v; w
(3, 3)
(3, 3)
sage: w = 22
sage: v; w
(3, 3)
22

more

Well, as an example: l = {1: v}; v.set(1,2) Now l == {1: (1, 2)}, but v = copy(w) does not change l...