0

Here's a method I have in a larger project (Python 3.8):

def generateTree(board, depth): #turns position into all of it's further branches
     
    branches = []  
    
    for i in range(64):
        for j in range(64): 
            if detLegality(board, i, j) == 'Legal':#finding a legal mov

                newPos = board
                newPos[j] = newPos[i]
                newPos[i] = ' ' 
                
                branches.append(newPos)
   
    return branches

The board parameter is not supposed to change inside the function, and I couldn't figure out why it was. After some debugging, I figured out it was changing during the two lines:

newPos[j] = newPos[i]
newPos[i] = ' '

How could a variable(board) change in a line that doesn't call it? I'm not an experienced coder, so what's going on here? Thanks.

  • 2
    See the line `newPos = board`? They are the same list. Assignment doesn't automatically create a copy. Quite the opposite, assigning creates a bind between a name and an object. So you just made `newPos` an alias to the same list `board` is an alias to. If you want a copy, you need to do this explicitly in Python – Tomerikoo Dec 10 '20 at 16:34
  • `newPos = board` means that `newPos` now points to the same list that `board` does. So any changes you make to `newPos` will affect `board`. – Random Davis Dec 10 '20 at 16:34
  • I didn't know it did that. What's the easiest way to make a clone of a variable that I could make changes to without affecting the original variable, then? – Joey Peluka Dec 10 '20 at 16:40
  • See this: https://nedbatchelder.com/text/names.html – juanpa.arrivillaga Dec 10 '20 at 16:40
  • @JoeyPeluka it depends on the object. Most built-in containers have a `.copy()` method that creates a shallow copy. For list objects, you will often see: `mylist[:]`. Again, these are *shallow* copies. See the linked duplicate – juanpa.arrivillaga Dec 10 '20 at 16:41
  • Is this exclusive to lists? For example, if I go: x = 1, y = x, y = 2, print(x). It prints a 1. – Joey Peluka Dec 10 '20 at 16:54
  • @JoeyPeluka no it is absolutely not exclusive to lists. The semantics of assignment *are exactly the same regardless of type*. Again, you should really read: https://nedbatchelder.com/text/names.html The example you gave is totally different, you are simply *re-assigning*, which doesn't change any `int` objects. `int` objects *happen* to be immutable, but look at this: `x = []; y = x; y = [42]; print(x)` and it still prints `[]` – juanpa.arrivillaga Dec 10 '20 at 20:07

0 Answers0