-2

Duplicate edit : There is another question that has been marked as similar, but it is different because it talks only about .append and full list instanciation. My issue is about offset assignement (data[j]) and iterators (used in the first function).


I'm being a little confused with Python by-object information passing. From my text book, when the function receive it's parameters, it creates an alias to the initial object. Also, about mutable param : "we note that reassigning a new value to a formal parameter, such as by setting list = [ ], does not alter the actual parameter; such reassignment breaks the alias".

Now I have these 2 functions :

def mult(data, factor):
    for val in data:
        val *= factor
data = [i for i in range(5)]
mult(data, 3)
print(data)

def mult2(data, factor):
    for j in range(len(data)):
        data[j] *= factor
data = [i for i in range(5)]
mult2(data, 3)
print(data)

This yields the output 0,1,2,3,4 and 0,3,6,9,12 respectively.

In mult2, we change the value of data by reassigning a new value. Why isn't the alias broken?

Additionnaly, in the first function, if I loop through every value of the list and I change it, is the alias broken?

Community
  • 1
  • 1
Maude
  • 512
  • 3
  • 8
  • 23
  • Try returning your values from the functions: `return val` Then store the result of the function as a variable and print that: `data = scale1(data, 3); print(data)` – GH05T Feb 12 '17 at 01:49
  • I know that val is just an int my problem is with data. Why isn't val changing the value of data? – Maude Feb 12 '17 at 02:30

1 Answers1

1

for val in data: val *= factor

You are reassigning val and so its "link" to data is broken

for j in range(len(data)): data[j] *= factor

You are using an "offset" from data, so the "link" doesn't get broken

Nullman
  • 4,179
  • 2
  • 14
  • 30
  • I get that, but why? I don't understand why using an offset doesn't break the link but simply looping through an iterator does? – Maude Feb 12 '17 at 02:29
  • 1
    this would make more sense if you knew c. let me try to explain: in the first approach, you are saying val is pointing at a value in a list, then you assign val a different value, you didn't change anything in the list you just tell cal to point at something else, so the list remains unchanged. in the second approach data is a list, think of data as something point at the beginning of a set of cells so `data[0] ` would give you the first cell in data, if you change it you change teh cell directly, not something pointing at it. does this make more sense? – Nullman Feb 12 '17 at 02:35
  • It's getting much clearer! Does this mean any action on data inside the function (append, remove, pop) will change the value outside of the function too? – Maude Feb 12 '17 at 02:43
  • 1
    yes, now you are getting it! – Nullman Feb 12 '17 at 02:45