Search code examples
pythonpython-3.xnestednested-lists

changes to my duplicate variable modify the original variable


If i define two variables

puzzle = [[1, 2, 3]]
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. How do I create a duplicate list without modifying the original list?

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 test_puzzle = puzzle[:], test_puzzle = list(puzzle) and test_puzzle = puzzle.copy() but all resulted in the same issue.

My code:

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

My output:

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