-4

This is hard for me to understand:

import numpy
f=numpy.array([1,2])
g=f
g[0]=f[0]+1
print(f)

The output of this code is [2,2]. How can I change the value of g without changing f?

E_net4
  • 27,810
  • 13
  • 101
  • 139
J. Ramos
  • 63
  • 7
  • Your question assumes that `f` and `g` are different, but they are just two different names for the same object. Python's `=` creates names. – Klaus D. Jan 30 '19 at 04:51
  • Ned batchelder wrote a really blog about this: [Facts and myths about Python names and values](https://nedbatchelder.com/text/names.html). One important point there is "Many names can refer to one value." and "Assignment never copies data" – MSeifert Jan 30 '19 at 05:00
  • @dyukha, FYI if you try to make a new question using the title I created: the question referenced does not show up in the results. – J. Ramos Jan 30 '19 at 05:46
  • @dyukha easy to say if you are an expert/already know the answer to what are you looking for, right?. As another comentator placed it,this is a very common question, so my advice would be to be more empathic the next time. – J. Ramos Jan 30 '19 at 06:03
  • 1
    @J.Ramos, Being common doesn't make it any good. It means that lots of people don't do research/minimize enough etc. You should just formulate your problem clearly enough. What you have done: you created a copy (at least you think so). What happens: when you change a copy, your original changes. Now you should place this into one sentence and google (with some keywords, like numpy). No "expert" skills required. –  Jan 30 '19 at 06:11
  • @dyukha Where did I say it was good? To spell it out, I meant that Python requires a change of paradigm for users of other programming languages, and you should be aware of that before calling out others ignorance every time. You must concede that the title was good enough to state the generalities of the problem because IT IS, what is done in the proposed code and it permited you (and others) to respond in context. – J. Ramos Jan 30 '19 at 17:23
  • Context, which is lost in this thread because some comments have been deleted (not by me) So further argumentation is pointless. – J. Ramos Jan 30 '19 at 17:51
  • What change of paradigm do you mean? You will get the same behavior in, say, Java. Like I said, your title is as good as empty string: no information there about the problem. –  Jan 30 '19 at 18:25

1 Answers1

1

This is because the way pointer work, you need to copy the variable not make a reference to it

In [16]: import copy
In [17]: import numpy
    ...: f=numpy.array([1,2])
    ...: g=copy.deepcopy(f)
    ...: g[0]=f[0]+1
    ...: print(f)
    ...:
    ...:
[1 2]

In [18]: f
Out[18]: array([1, 2])

In [19]: g
Out[19]: array([2, 2])