1

Here are two methods. One modifies the variable x, the other does not. Can you please explain to me why this is?

x = [1,2,3,4]
def switch(a,b,x):
     x[a], x[b] = x[b], x[a]
switch(0,1,x)
print(x)
[2,1,3,4]


def swatch(x):
    x = [0,0,0,0]

swatch(x)
print(x)
[2,1,3,4]
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
jsmith
  • 295
  • 1
  • 3
  • 9

1 Answers1

3

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.

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677