0

I am trying to implement some sort of local search. For this I have two arrays, which represent a list, that I am trying to optimize. So I have one array as the current best array and the one I am currently analyzing.

At the beginning I am shuffling the array and set the current best array to the shuffled array.

random.shuffle(self.matchOrder)
self.bestMatchOrder = self.matchOrder

Then I am swapping a random neighboured pair in the array. Now the problem I have is that when I am swapping the values in self.matchOrder, the values in self.bestMatchOrder get swapped.

a = self.matchOrder[index]
self.matchOrder[index] = self.matchOrder[index + 1]
self.matchOrder[index + 1] = a

"index" is given to the function as a parameter, it is just randomly generated number.

I guess I did something wrong assigning the variables, but I can't figure out what. So what can I do to only assign the value of the array to the other array and not make it apply the same changes to it, too?

2 Answers 2

3

When you use self.bestMatchOrder = self.matchOrder Then Python doesn't allocates a new memory location to self.bestMatchOrder instead both are pointing to the same memory location. And knowing the fact that the lists are mutable data type, Hence any changes made in the self.matchOrder would get reflected in the self.bestMatchOrder.

import copy

self.bestMatchOrder = copy.deepcopy(self.matchOrder)

However if you are using linear lists or simple lists the you can also use self.bestMatchOrder = self.matchOrder[:] But if yo are using nested lists then deepcopy() is the correct choice.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this very fast answer :) I already thought of something like this. What gets me confused, why do I make bestMatchOrder still pointing to a different memory location after I initialized it in the Object initialization?
0

If you want to copy a list, you can use slice operation:

list_a = [1, 2, 3]
list_b = list_a[:]
list_a = [0, 0, 42]
print list_a  # returns [0, 0, 42]
print list_b  # returns [1, 2, 3], i.e. copied values

But if you have more complex structures, you should use deepcopy, as @anmol_uppal advised above.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.