I\'m trying to understand Python\'s approach to variable scope. In this example, why is f()
able to alter the value of x
, as perceived within
f
doesn't actually alter the value of x
(which is always the same reference to an instance of a list). Rather, it alters the contents of this list.
In both cases, a copy of a reference is passed to the function. Inside the function,
n
gets assigned a new value. Only the reference inside the function is modified, not the one outside it.x
does not get assigned a new value: neither the reference inside nor outside the function are modified. Instead, x
’s value is modified.Since both the x
inside the function and outside it refer to the same value, both see the modification. By contrast, the n
inside the function and outside it refer to different values after n
was reassigned inside the function.