Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

writing a deepcopy without using deepcopy

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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,
]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading