-1

When using a function in phyton, I am taught that actually a copy of my value is parsed. In the example shown below apply a function onto a Parameter a. Here, I expected that a copy of a is sent to the function fun. In this function, only the copy of a is available, not parameter a on a global scope. I even gave it another Name: b. When I modify the value b in my function, then also the Parameter a on the global scope is changed. Is this supposed to be correct?

import numpy as np

def fun(b):
    b += np.array([1,1])

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

fun(a)

print(a)

I expected to get np.array([1,1]), but I get np.array([2,2])

This happens only, when I use the += Operator in the function fun. If I use b = b + np.array([1,1]) instead, the value of a on global scope stays the same.

Till Hoffmann
  • 9,479
  • 6
  • 46
  • 64
  • In `def fun(b)`, the paramter `b` was passed in by reference. While you run the following, you will understand the issue: ``` import numpy as np def fun(b): print(['in def fun(b)', id(b)]) b += np.array([1, 1]) a = np.array([1, 1]) print(id(a)) fun(a) print(id(a)) print(a) ``` – caot Oct 24 '19 at 14:04
  • @Till Hoffmann the [duplicate] mark is kinkd of wrong. – caot Oct 24 '19 at 14:06

2 Answers2

0

In python the list datatype is mutable, that means that every time you run your function, a list will keep growing.

The key moment is here: b += np.array([1,1])

You already got a, which is [1, 1] and you adding it to another array which is [1, 1] and you are getting [2, 2] which is how it should be.

You are ending up modifying the a

inmate_37
  • 1,218
  • 4
  • 19
  • 33
0

When you call fun() you don't make a copy of a and modify b, rather, a itself is passed to fun() and refered to as b in there.

As such,

b += np.array([1,1])

modifies a.

Jeffrey
  • 11,063
  • 1
  • 21
  • 42