python - Explain this inconsistency -


here 2 methods. 1 modifies variable x, other not. can please explain me why 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] 

the function definition

def swatch(x): 

defines x local variable.

x = [0, 0, 0, 0] 

reassigns local variable x new list. not affect global variable x of same name.


you remove x arguments of swatch:

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

but when python encounters assignment inside function definition like

x = [0, 0, 0, 0] 

python consider x local variable default. assigning values x not affect global variable, x.

to tell python wish x global variable, need use global declaration:

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

however, in case, since x mutable, define swatch this:

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

although x inside swatch local variable, since swatch called

swatch(x)  # global variable x 

it points same list global variable of same name.

x[:] = ... alters contents of x, while x still points original list. thus, alters value global variable x points too.


def switch(a,b,x):      x[a], x[b] = x[b], x[a] 

is example contents of x mutated while x still points original list. mutating local x alters global x well.


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -