copy of array gets overwritten in function

I am trying to create an array np.zeros((3, 3)) outside a function and use it inside a function over and over again. The reason for that is numba's cuda implementation, which does not support array creation inside functions that are to be run on a gpu. So I create aforementioned array ar_ref , and pass it as argument to function. ar creates a copy of ar_ref (this is supposed to be used as "fresh" np.zeros((3, 3)) copy). Then I perform some changes to ar and return it. But in the process ar_ref gets overwritten inside the function by the last iteration of ar. How do I start every new iteration of the function with ar = np.zeros((3, 3)) without having to call np.zeros inside the function?

import numpy as np

def function(ar_ref=None):
    for n in range(3):
        print(n)
        ar = ar_ref
        print(ar)
        for i in range(3):
            ar[i] = 1
        print(ar)
    return ar

ar_ref = np.zeros((3, 3))
function(ar_ref=ar_ref)

Output:

0
[[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]
[[1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]]
1
[[1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]]
[[1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]]
2
[[1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]]
[[1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]]

Upvotes: 1

Views: 72

Answers (1)

Javad Rezaei
Javad Rezaei

Reputation: 1110

simple assignment will only assign pointer, so when you change ar, ar_ref changes too. try to use shallow copy for this issue

import numpy as np
import copy 

def function(ar_ref=None):
    for n in range(3):
        print(n)
        ar = copy.copy(ar_ref)
        print(ar)
        for i in range(3):
            ar[i] = 1
        print(ar)
    return ar

ar_ref = np.zeros((3, 3))
function(ar_ref=ar_ref)

output:

0
[[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]
[[1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]]
1
[[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]
[[1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]]
2
[[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]
[[1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]]

Upvotes: 2

Related Questions