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

changes to my duplicate variable modify the original variable

If i define a variable called puzzle = [[1, 2, 3]] and then make another variable called test_puzzle = puzzle when modifying test_puzzle the change is applied to puzzle as well. I do not want to modify the original puzzle variable, is there anyway I am able to create a duplicate without modifying the original value and without the need for loops

I found solutions here:
python: changes to my copy variable affect the original variable

and here:
How do I clone a list so that it doesn't change unexpectedly after assignment?

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

I tried to do test_puzzle = puzzle[:], test_puzzle = list(puzzle) and test_puzzle = puzzle.copy() as described but all resulted in the same issue.

    puzzle = [[1, 2, 3]]
    test_puzzle = puzzle
    test_puzzle[0][1] = 7
    print(puzzle)
    print(test_puzzle)```

-> [[1, 7, 3]]
-> [[1, 7, 3]]

>Solution :

[:] or copy doesn’t copy the list inside the outer list

So you’re changing the same object, but you can use deepcopy to fix that, or simple copy the list inside:

from copy import deepcopy

puzzle = [[1, 2, 3]]
test_puzzle = deepcopy(puzzle)
# or
# test_puzzle = [x[:] for x in test_puzzle]
test_puzzle[0][1] = 7
print(puzzle)
print(test_puzzle)

will result in

[[1, 2, 3]]
[[1, 7, 3]]
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