Suppose I have a list as such li = [1, 2, 3, 4, 5]
and a scale function as
def scale(data, factor):
for j in range(len(data)):
data[j] *= factor
Now if I pass li
to scale
function with a factor = 2
, my list gets modified. That is the actual parameter gets changed here. So if i print li
after executing the above function it gives [2, 4, 6, 8, 10]
and not the original one.
Another way scale function is implemented is as follows:-
def scale(data, factor):
for val in data:
val *= factor
Now if I execute scale(li, 2)
then it doesn't modify the actual parameter. So li
stays as [1, 2, 3, 4, 5]
.
So my question is why does one modify the list and the other doesn't?
Has this got anything to do with mutability or immutability?