The function definition
def swatch(x):
defines x
to be a local variable.
x = [0, 0, 0, 0]
reassigns the local variable x
to a new list.
This does not affect the global variable x
of the same name.
You could remove x
from the arguments of swatch
:
def swatch():
x = [0, 0, 0, 0]
but when Python encounters an assignment inside a function definition like
x = [0, 0, 0, 0]
Python will consider x
a local variable by default. Assigning values to this x
will not affect the global variable, x
.
To tell Python that you wish x
to be the global variable, you would need to use the global
declaration:
def swatch():
global x
x = [0,0,0,0]
swatch()
However, in this case, since x
is mutable, you could define swatch
like this:
def swatch(x):
x[:] = [0,0,0,0]
Although x
inside swatch
is a local variable, since swatch
was called with
swatch(x) # the global variable x
it points to the same list as the global variable of the same name.
x[:] = ...
alters the contents of x
, while x
still points to the original list. Thus, this alters the value that the global variable x
points to too.
def switch(a,b,x):
x[a], x[b] = x[b], x[a]
is another example where the contents of x
are mutated while x
still points to the original list. Thus mutating the local x
alters the global x
as well.