Skip to content Skip to sidebar Skip to footer

Why Does My Original List Change?

I a wrote a function SwapCities that is able to swap entries 3 and 4 in a list. So f.e. [0,1,2,3,4] should become [0,1,2,4,3]. This function works perfectly, but strangely my origi

Solution 1:

SwapCities is mutating the contents of solution. Since solution points to the same list as IncumbentSolution, the values inside IncumbentSolution are altered too.


To preserve the original values in IncumbentSolution, make a new copy of the list:

tmpsolution = list(IncumbentSolution)

makes a shallow copy of the the original list. Since the contents of IncumbentSolution are immutable numbers, a shallow copy suffices. If the contents included, say, dicts which were also being mutated, then you would need to make a deep copy of the list:

importcopy
tmpsolution = copy.deepcopy(IncumbentSolution)

Solution 2:

That's because you modified the list inside the function.

By passing the list to the function you simply created another reference to the same object, solution and IncumbentSolution actually point to the same list object.

You should pass a shallow copy to the function, using IncumbentSolution[:].

>>>deffunc(x):...returnid(x)...>>>lis = range(5)>>>id(lis),func(lis)     #both `x` and `lis` point to the same object
(163001004, 163001004)

>>>id(lis),func(lis[:])  #pass a shallow copy, `lis[:]` or `list(lis)`
(163001004, 161089068)

Post a Comment for "Why Does My Original List Change?"