Home > Mobile >  Python True Copy Within a Class
Python True Copy Within a Class

Time:05-28

For some reason, I have a list that keeps getting modified despite being explicitly a deep copy. It appears to be unmodified as it goes through the loop, but it suddenly is modified once it exists? I must be missing something that pertains to Python's rules and logic, but I can't figure it out for the life of me.

def all_possible_states(self):
    #creates many variations of a board from the available set of moves
    to_return = [] #list of possible board states to return
    #print(self.availible_moves)
    list_to_copy = copy.deepcopy(self.availible_moves)
    for item in self.availible_moves:
        print('loop')
        
        #append possible board state to list. set of availible moves for that board is one less. Done by removing item from that move list
        to_return.append(board(self.player, copy.deepcopy(self.board.copy()), list_to_copy, self.plays, self.score, copy.deepcopy(item)))
        
        #print(item)
        print( self.avalible_moves) #shows the total set of moves. This is unmodified whenever it prints
        print(list_to_copy)#deep copy of the original list. This is unmodified when it prints
        print(to_return[len(to_return) - 1].availible_moves) #List of moves left availible for the board, this slowly shrinks for some reason each loop
    
    
    print(self.availible_moves) #this is the original list, but it's not basically been cut all the way down for some reason
    return to_return

CodePudding user response:

Notice, the local variable list_to_copy is the deepcopy, not self.availible_moves. You are saving a deepcopy of self.availible_moves and it is being stored in the list_to_copy variable you defined. list_to_copy never changes as expected from a deepcopy. I'm not exactly sure what you are trying to do, but if you want, at the end you can reset self.availible_moves to be equal to list_to_copy and then it will be as if it never changed.

EDIT:

Actually, I think you have a spelling mistake, notice that you print(self.avalible_moves) and you are saying its not changing, when really what is changing is self.availible_moves. Notice the extra letter i in the first expression. This definitely is one of your problems.

  • Related