On Jun 12, 2010, at 17:27 , Byungchul Cha wrote:


Please tell me if this is a bug, or, I'm missing something obvious...

sage: a = 3 # Assign a value to a variable a
sage: b = a # Create a copy of a
sage: b = 2 # Change the value of b
sage: b
2
sage: a # The value of a remains unchanged, as expected.
3

So far, it looks good to me. But, when I do a similar thing with
matrices, it doesn't look to be the same.

sage: v = matrix(ZZ, 3, range(9))
sage: u = v
sage: u[2] = [0,0,0]
sage: u
[0 1 2]
[3 4 5]
[0 0 0]
sage: v
[0 1 2]
[3 4 5]
[0 0 0]

Shouldn't the value of v remain the same? Why does the change in u
(or, a row of u) affect v?

You might think the behavior should be the same, but that's not the case. Objects with structure (matrices, for example) are copied "by reference", while things like integers, which have little or no structure (from the user's perspective at any rate) are copied "by value".

What that means is that, for matrices, "u=v" means that the names u,v now refer to the same Sage object, so when you modify one, you are modifying the other (since you are really modifying the underlying object).

For, e.g., integers, "u=v" means that the names u,v both refer to their own copies of the value in question.

This is, BTW, the way Python works, and Python is the language with which (most of) Sage is implemented.

In case you didn't already know that :-}

HTH.

Justin

--
Justin C. Walker, Curmudgeon at Large
Director
Institute for the Enhancement of the Director's income
-----------
--
They said it couldn't be done, but sometimes,
it doesn't work out that way.
  - Casey Stengel
--



--
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/sage-support
URL: http://www.sagemath.org

Reply via email to