Search code examples
pythonrecursionbacktracking

Print prints the right value but the appends different value to list


I am trying to code the solution to a backtracking problem online.

I face a very weird problem with the code.

The print statement seems to be printing the exact array that I want, but a different one gets appended to the list when the two lines are consecutive

class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        def backtrack(index):
            if index==len(nums):
                print(nums)
                permutations.append(nums)
            else:
                for i in range(index,len(nums)):
                    temp = nums[index]
                    nums[index] = nums[i]
                    nums[i] = temp
                    backtrack(index+1)
                    temp = nums[index]
                    nums[index] = nums[i]
                    nums[i] = temp
        permutations = []

        backtrack(0)
        return permutations

The expected output is shown below the print statement prints

[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 2, 1]
[3, 1, 2]

But the value I see in the permutations array is

[[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3]]

which is extremely weird. Can someone help me out with this?


Solution

  • When you call permutations.append(nums), you're not appending a copy of nums -- you're appending a reference to the actual nums object. This means if nums ever changes, all of the references change too, because they're all the same object.