I understand that arrays are mutable. So if I have a function like:
def foo(xs):
xs.append(4)
>>> xs = [1,2,3]
>>> foo(xs)
>>> xs
[1,2,3,4]
This makes sense to me. However what happens during array assignment like this?
def foo(xs):
ys = ['a','b','c']
xs = ys
>>> xs = [1,2,3]
>>> foo(xs)
>>> xs
[1,2,3]
Why doesn't the change of reference in the function change what xs
points to outside foo
? My guess is that when the assignment happens, a new reference also called xs
is created meaning that the input argument is no longer accessible. However, if I wanted this behavior (reassigning the values of an array in a function), is there an easier way than iterating over each element in a manner such as:
def foo(xs):
ys = ['a','b','c']
for idx, item in enumerate(ys):
xs[i] = item