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
Post a Comment