0

I was trying to translate my code to python to print all possible permutation of a list. My code goes below:

def helper(A, l, r, ans):
    if l == r:
        print(A)
        ans.append(A)
    else:
        for i in range(l, r + 1):
            A[l], A[i] = A[i], A[l]
            helper(A, l+1, r, ans)
            A[l], A[i] = A[i], A[l]
def permute(A):
    ans = []
    helper(A, 0, len(A)-1, ans)
    print(ans)

permute([1, 2, 3])
Strangely I get this as output:
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 2, 1]
[3, 1, 2]
[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]] 

What is going on here?

Robur_131
  • 674
  • 1
  • 5
  • 16
  • It's because `A` keeps getting changed, and your list is just `[A, A, ..., A]`. Take a copy of `A` instead with `ans.append(list(A))`. – Loocid Jun 15 '21 at 07:54
  • @Loocid i dont get why append is not picking changes in A. Can you please explain that? – ayush songra Jun 15 '21 at 08:07
  • @ayushsongra ```ans.append(A)``` - Here you are appending the reference of list ```A``` to ```ans```. Finally ```ans``` will have all ```A``` s in it like @Loocid said above. – Ram Jun 15 '21 at 08:22
  • @ayushsongra Append is picking up the changes. But whenever you change one entry, it changes all of them because they all point to the same list object, which is why you need to take a copy of that object instead. – Loocid Jun 15 '21 at 14:15
  • Does this answer your question? [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – Henry Ecker Jun 15 '21 at 22:53
  • If it is not for learning purposes, consider using [`itertools.permutations`](https://docs.python.org/3/library/itertools.html#itertools.permutations) instead. – Lenormju Jun 16 '21 at 07:42

0 Answers0