Home > Enterprise >  changes to my duplicate variable modify the original variable
changes to my duplicate variable modify the original variable

Time:06-15

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?

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]]

CodePudding user response:

[:] 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]]
  • Related