0

I am kind of a newbie in python and this puzzles me for a while.

I wrote the code below:

pool = np.array([[1,1],[1,1]])

def ringDisc(data):
    data_new = data
    data_new[1] = 0
    return data_new

print(pool)
print(ringDisc(pool))
print(pool)

I expect the result should be [[1,1],[1,1]] for the first "print" and [[1,1],[0,0]]for the second "print" and [[1,1],[1,1]] for the last.

But what I got from this is [[1,1],[1,1]]; [[1,1],[0,0]]; [[1,1],[0,0]].

could anyone help me with this and explain why my code doesn't work out in the way I want? thank a lot!

Veronica
  • 43
  • 5
  • For the "Why this happens" (which is not very intuitive and actually quite a complex issue under-the-hood): https://stackoverflow.com/questions/11585793/are-numpy-arrays-passed-by-reference – GPhilo Oct 28 '19 at 13:34
  • In python, `pool`, `data`, `data_new` all reference the same object. None of the steps makes a copy. – hpaulj Oct 28 '19 at 15:15

2 Answers2

1

You can do the following:

data_new = np.copy(data)

Inside ringDisc

So with this change, the code looks like this:

import numpy as np

pool = np.array([[1, 1], [1, 1]])


def ringDisc(data):
    data_new = np.copy(data)
    data_new[1] = 0
    return data_new


print(pool)
print(ringDisc(pool))
print(pool)

The result:

[[1 1], [1 1]]
[[1 1], [0 0]]
[[1 1], [1 1]]

As expected.

Rafael
  • 7,002
  • 5
  • 43
  • 52
  • No problem! Glad that this helped you. – Rafael Oct 28 '19 at 13:44
  • @Veronica If that solved your problem, please consider accepting this answer or any other answer that solved your problem by clicking the "tick" button next to the corresponding answer. – Rafael Nov 27 '19 at 10:27
0

In numpy views and copy are two different concept, in your case you want to modify a copy of your data. An interesting article about that.

As mentioned by @Rafael, you could do somehting like this.

pool = np.array([[1,1],[1,1]])

def ringDisc(data):
    data_new = np.copy(data) # <===== Here 
    data_new[1] = 0
    return data_new

print(pool)
print(ringDisc(pool))
print(pool)
Florian Bernard
  • 2,561
  • 1
  • 9
  • 22
  • @GPhilo When I have writen this awnser, existing code was not yet there ! @Rafael only put `data_new = np.copy(data)` as an awser. I have also upvote its awser. – Florian Bernard Oct 28 '19 at 13:39