Difference between a list and list[:]?

Viewed 27

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

0 Answers
Related