Merksem09
Merksem09

Reputation: 9

How to store a variable that don't change

I'm backtracking something for game like candycrush... And of course for my backtracking I need to change my initial board all the time... But at the end of the game, it doesn't return the old_board.. How can I change that

I tried with a function:

def return_original_board(board):
    original_board = []
    for i in board:
        original_board.append(i)
    return original_board

And in my backtracking function I made a variable that stored this function, but I still change everything and I can't use the copy() function

Upvotes: 0

Views: 69

Answers (1)

user2390182
user2390182

Reputation: 73450

Since board is a 2-dim list, i in your code is a list, too. Then, you will still be mutating those lists during the game. Change as follows:

for i in board:  # if board is a nested list, i is a list
    original_board.append(i[:])  # use a copy of the list

Or even shorter (using a list comprehension and more telling variable name):

def return_original_board(board):
    return [row[:] for row in board]

Upvotes: 3

Related Questions