Passing by reference? An copied array question...

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • pholvey
    New Member
    • Jun 2008
    • 3

    Passing by reference? An copied array question...

    Hi guys. I'm brand new to this forum, so if I'm messing up by starting my own thread, I'm sorry. But this array problem I'm running into has got me hitting a brick wall.

    I'm in Python, and I've imported Numeric. And I'm on Fedora.

    I'm trying to make a copy of a 3x3 array, modify the copy, then subtract the original array from the copy to see what's left. But every time I change the copy, the original changes too, so the final difference between the two 3x3 arrays is 0 in every element.

    I looked around online and it looks like Python passes by reference, right? So whatever I do to the "copied" array is passed back to the original. I saw somewhere that

    Code:
    ..newarray = oldarray[:]..
    was supposed to make a physical copy and avoid the problem, but it didn't work for me.

    Here's what I'm running:

    Code:
    ..sitewater=masterwater[:]
    print masterwater
    print sitewater
    sitewater[2,0]=3
    print sitewater
    print masterwater..
    and the output is:

    Code:
    ..[[  2.157016   0.931734  18.799198]
     [  1.484143   2.309928  18.915375]
     [  1.283086   1.359119  18.840746]]
    [[  2.157016   0.931734  18.799198]
     [  1.484143   2.309928  18.915375]
     [  1.283086   1.359119  18.840746]]
    [[  2.157016   0.931734  18.799198]
     [  1.484143   2.309928  18.915375]
     [  3.         1.359119  18.840746]]
    [[  2.157016   0.931734  18.799198]
     [  1.484143   2.309928  18.915375]
     [  3.         1.359119  18.840746]]..
    Any ideas? Any advice on how to better ask questions would be appreciated too!

    Thanks,
    pholvey
  • jlm699
    Contributor
    • Jul 2007
    • 314

    #2
    [code=python]
    import copy
    newObj = copy.deepcopy(o ldObj)
    [/code]

    this will prevent the "shallow copy" problem of which you speak.

    Comment

    • pholvey
      New Member
      • Jun 2008
      • 3

      #3
      Looks like it worked just fine. Thanks guys!

      pholvey

      Originally posted by jlm699
      [code=python]
      import copy
      newObj = copy.deepcopy(o ldObj)
      [/code]

      this will prevent the "shallow copy" problem of which you speak.

      Comment

      Working...