0

So I was solving this question Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order. (Leetcode 46) here is my solution to it

def rec(index, nums, ans):
    if(index == len(nums)):
        ans.append(nums)
        return
    for i in range(index, len(nums)):
        nums[index], nums[i] = nums[i], nums[index]
        rec(index+1, nums, ans)
        nums[index], nums[i] = nums[i], nums[index]

the output when nums is [1,2,3] is

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

but my output differs when I change ans.append(nums) to ans.append(nums[:]) the output is

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

JRose
  • 1,382
  • 2
  • 5
  • 18
  • `[:]` creates a new array on which the values are copied, without you are just copying the reference to the array itself, so you have 2 variables pointing to the same area of memory, this answer has a way better explanation https://stackoverflow.com/questions/2612802/how-do-i-clone-a-list-so-that-it-doesnt-change-unexpectedly-after-assignment/2612815#2612815 – Alberto Sinigaglia Sep 08 '22 at 16:09
  • @AlbertoSinigaglia The values aren't copied at all when you do `[:]`. It is a "shallow" copy. And while I guess you can say "copying the reference to the list", it is simpler to say that without it, *you aren't copying anything at all* and you are just appending the same list object – juanpa.arrivillaga Sep 08 '22 at 16:10
  • @juanpa.arrivillaga they are both called copy, one is copy by value and the other one is copied by reference, at least I come from C++, and they are called like this – Alberto Sinigaglia Sep 08 '22 at 16:12
  • @AlbertoSinigaglia yeah, but **this isn't C++**. This is Python. In Python, one is a copy, a shallow copy, the other *isn't a copy at all*. Assignment doesn't copy. Python variables and C++ variables are different things altogether. In Python, a variable is just a name in a namespace that references an object. In C++, a variable is a named area of memory. Python is at a much higher level of abstraction – juanpa.arrivillaga Sep 08 '22 at 16:13

0 Answers0