python - Why does my original list change? -


i wrote function swapcities able swap entries 3 , 4 in list.

so f.e. [0,1,2,3,4] should become [0,1,2,4,3]. function works perfectly, strangely original list changes not want.

this code:

def swapcities(solution):     n = 3##randint(0,numberofcities-1)     m = 4##randint(0,numberofcities-1)     result = solution     temp1 = solution[n]     temp2 = solution[m]     result[n] = temp2     result[m] = temp1     return result 

print "start" incumbentsolution = list(x x in range(0,numberofcities)) print incumbentsolution  print "after swap" newsolution = swapcities(incumbentsolution) print newsolution  print "original solution" print incumbentsolution 

i following result:

how many cities? 8 start [0, 1, 2, 3, 4, 5, 6, 7] after swap [0, 1, 2, 4, 3, 5, 6, 7] original solution [0, 1, 2, 4, 3, 5, 6, 7]   (why did change?!) 

as can see original solution changed should not do.

i have no clue why happens. when change code such changes applied copy of original list result. explain doing wrong?

incumbentsolution = list(x x in range(0,numberofcities)) print "start" print incumbentsolution  print "after swap" tmpsolution = incumbentsolution newsolution = swapcities(tmpsolution) print newsolution  print "original solution" print incumbentsolution 

swapcities mutating contents of solution. since solution points same list incumbentsolution, values inside incumbentsolution altered too.


to preserve original values in incumbentsolution, make new copy of list:

tmpsolution = list(incumbentsolution) 

makes shallow copy of the original list. since contents of incumbentsolution immutable numbers, shallow copy suffices. if contents included, say, dicts being mutated, need make deep copy of list:

import copy tmpsolution = copy.deepcopy(incumbentsolution) 

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 -