So I need to make a deepcopy of a nested list but without using the import copy. I have a sepereate function that outputs Board
Board = [['B', 'B', 'B', 'B', 'B'], ['B', 'B', 'B', 'B', 'B'], ['B', 'B', '', 'W', 'W'], ['W', 'W', 'W', 'W', 'W'], ['W', 'W', 'W', 'W', 'W'], 0]
So I thought of doing this to make a deepcopy using for loop:
def copy(b: Board) -> Board:
if isinstance(b, list):
return [copy(item) for item in b]
else:
return b
But when doing this I think I just returns b without making a deepcopy, since the 0 at the end is an integer?
Am I also correct in thinking that to test if I made a correct deepcopy I can do the following to confirm:
copy == Board
True
copy is Board
False
when returning copy i get the following:
[['B', 'B', 'B', 'B', 'B'], ['B', 'B', 'B', 'B', 'B'], ['B', 'B', '', 'W', 'W'], ['W', 'W', 'W', 'W', 'W'], ['W', 'W', 'W', 'W', 'W'], 0]
but when trying to test with "==" and "is" I get:
copy == make_Board
False
copy is make_Board
False
>Solution :
To make a copy of the Board you can use next example:
Board = [
["B", "B", "B", "B", "B"],
["B", "B", "B", "B", "B"],
["B", "B", "", "W", "W"],
["W", "W", "W", "W", "W"],
["W", "W", "W", "W", "W"],
0,
]
def copy_board(b):
return [item[:] if isinstance(item, list) else item for item in b]
new_Board = copy_board(Board)
new_Board[0][0] = "XXX"
print(Board)
print(new_Board)
Prints:
[
["B", "B", "B", "B", "B"],
["B", "B", "B", "B", "B"],
["B", "B", "", "W", "W"],
["W", "W", "W", "W", "W"],
["W", "W", "W", "W", "W"],
0,
]
[
["XXX", "B", "B", "B", "B"],
["B", "B", "B", "B", "B"],
["B", "B", "", "W", "W"],
["W", "W", "W", "W", "W"],
["W", "W", "W", "W", "W"],
0,
]