The following behavior is very confusing to me.

I define a program

def test(a):
    b=a
    b = a^2
    return b

Then if I assign
x = 2
and then execute
test(x)
    4
I get x squared and x  unchanged:
x
    2

However suppose now that I want the same on a single
element of a matrix and define

def testmatrix(a):
    b=a
    b[1,1] = a[1,1]^2
    return b

Then I set

m = identity_matrix(2)*2

Thus:

m
    [2 0]
    [0 2]

Now with

testmatrix(m)

    [2 0]
    [0 4]

I get what I wanted, but...
now also m is changed !

m
    [2 0]
    [0 4]

Outside the program !

I expected  m to  be
    [2 0]
    [0 2]
the same before the program executed.
The problem is solved by changing the program to

def testmatrix(a):
    b=a.copy()
    b[1,1] = a[1,1]^2
    return b

However, it is confusing to have a function with local variable a
that returns another variable b locally equal to a and changes
the value of a outside the function.

-- Giovanni

--~--~---------~--~----~------------~-------~--~----~
To post to this group, send email to sage-support@googlegroups.com
To unsubscribe from this group, send email to 
sage-support-unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/sage-support
URLs: http://www.sagemath.org
-~----------~----~----~----~------~----~------~--~---

Reply via email to