python - Variable overwritten inside a function -


i have following piece of code in python 2.7

abc=[[1,2,3],[0,1,2]] def make_change(some_list):     in range(len(some_list)):         if some_list[i][0]==0:             some_list[i]=[]     return some_list  new_list=make_change(abc)  print abc print new_list 

my understanding should produce following output.

[[1,2,3],[0,1,2]]

[[1,2,3],[]] 

but python produces

[[1,2,3],[]]   [[1,2,3],[]] 

am missing something?

you can prevent issue copying list while passing function:

abc=[[1,2,3],[0,1,2]] def make_change(some_list):     in range(len(some_list)):         if some_list[i][0]==0:             some_list[i]=[]     return some_list  new_list=make_change(abc[:])  print abc print new_list 

the changed part:

new_list=make_change(abc[:]) 

the reason happens python passes list reference, changes made original well. using [:] creates shallow copy, enough prevent this.


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -