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

2
  • 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) ``` Commented Oct 24, 2019 at 14:04
  • @Till Hoffmann the [duplicate] mark is kinkd of wrong. Commented Oct 24, 2019 at 14:06

2 Answers 2

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.

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

Comments

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

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.