-1

I have list of int's called board in python code. I wan't to know, if it was modified, so I have code

self.oldboard = list(self.board)
#here is board modified, if it is possible
if not self.oldboard == self.board:
    #this should execute only when board was modified

But oldboard is always equals to board, when I modify board, it modifies oldboard. How to make oldboard just copy of board, not reference?

parman
  • 127
  • 1
  • 3
  • 11

2 Answers2

3

When copying lists by the slice method (analogous to what you're currently doing):

new_list_copy = old_list[:]

you'll only get a "shallow" copy of the contents. This isn't suitable for lists that contain lists ("nested lists").

If you're trying to copy a nested list, a Pythonic solution is to use deepcopy from the copy module:

import copy
new_list_copy = copy.deepcopy(old_list)
  • Downvote for what? Preferred to dupe target the question? –  Feb 10 '15 at 19:04
  • 1
    I don't understand it either, +1 for valid method IMO. – HavelTheGreat Feb 10 '15 at 19:06
  • probably because your first answer is incorrect, what do you think `list(self.board)` is doing? – Padraic Cunningham Feb 10 '15 at 19:10
  • @PadraicCunningham I'm aware that the first option is analogous to what the OP is doing, which is why I added the explanation of "if you have nested lists." My thinking is that the OP might see a slice copy and get confused, where the deepcopy comes with a "use this if" and a link to the doc. –  Feb 10 '15 at 19:12
  • `old_list[:]` is exactly the same as `list(old_list)` so if that does not work `old_list[:]` won't work – Padraic Cunningham Feb 10 '15 at 19:13
  • @PadraicCunningham yes, I'm aware. I took your feedback and added why I mentioned slice copy to the answer. Thanks! –  Feb 10 '15 at 19:14
  • Better of removing it as it is more confusing than helpful, if you explained the difference between a shallow and a deep copy that would be a lot more useful than suggesting something exactly the same just syntactically different. – Padraic Cunningham Feb 10 '15 at 19:16
  • I'll change the language of why I listed it, but I'm leaving it in. Answers meant to copy-and-paste don't teach anything. –  Feb 10 '15 at 19:17
  • Thanks, deepcopy works – parman Feb 10 '15 at 19:27
0

Integers are immutable. I would recommend you familiarize yourself with the notions of shallow and deep copy operations, which you can find in the Python Docs here .

In your case you most likely need to use deepcopy, as I would guess that you have several nested lists.

HavelTheGreat
  • 3,299
  • 2
  • 15
  • 34