-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?

8
  • Your question assumes that f and g are different, but they are just two different names for the same object. Python's = creates names. Commented Jan 30, 2019 at 4:51
  • Ned batchelder wrote a really blog about this: Facts and myths about Python names and values. One important point there is "Many names can refer to one value." and "Assignment never copies data" Commented Jan 30, 2019 at 5: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. Commented Jan 30, 2019 at 5: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. Commented Jan 30, 2019 at 6: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. Commented Jan 30, 2019 at 6:11

1 Answer 1

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])

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.