0

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
CoconutBandit
  • 476
  • 1
  • 3
  • 13
  • Because you're not changing the object that you pass into `foo` at all. You're just throwing it away. The name doesn't matter, only the object it refers to. – Morgan Thrapp Nov 08 '16 at 19:29
  • Because Python is pass-by-value, you get a copy of the reference (NOT a copy of the value!) in the function parameter. – dhke Nov 08 '16 at 19:30
  • @dhke - Passing a copy of the reference means Python is pass-by-reference, not pass-by-value. – TigerhawkT3 Nov 08 '16 at 19:31
  • @TigerhawkT3 That's been argued before quite heavily and opinions still differ. Hence the additional explanation: You get a copy of the object reference. – dhke Nov 08 '16 at 19:32

0 Answers0