0

Function 1

def scale(data, factor):
    for j in data:
        j = j * factor

target = [1,2,3,4,5]
factors = 4

scale(target, factors)
print(target)

Output = [1, 2, 3, 4, 5]

Function 2

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

target = [1,2,3,4,5]
factors = 4

scale(target, factors)
print(target)

Output [4, 8, 12, 16, 20]

Why is it that in the first function i dont get the output but when i use the range function i suddenly do?

  • `data[j] *= factor` is `data[j] =data[j]* factor` will you use `__setitem__` which will set item in place. – Ch3steR Mar 20 '20 at 13:08
  • 1
    [Function changes list values and not variable values in Python](https://stackoverflow.com/questions/17686596/function-changes-list-values-and-not-variable-values-in-python) – pault Mar 20 '20 at 13:10

1 Answers1

1

The difference is in the way you are accessing those arrays. The in the first case

for j in data:
    j = j * factor

You access each j <int> in data. Since in Python, variables of type int are immutable, by doing j = j * factor, you make a new variable called j with new memory, the old j is still referenced by 'data', but the old j's memory did not change here. Crucially, data is still referencing the old j, so it does not change.

In contrast, when doing

for j in range(len(data)):
    data[j] =  data[j] * factor # <- equivalent to *=

You get a pointer to the j-th element of data, multiply it's value by factor, and setdata[j] to be that new value.

AlexNe
  • 926
  • 6
  • 22