0

i want to know the difference between list variable itself and listvariable followed by [:]

for example,

# When nums are List[int] and res are List,
# what is the difference between
res.append(nums[:])
# and 
res.append(nums)

my question came up while i'm implementing recursive permutation function

class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        res = []
        self.helper(nums, 0, len(nums) - 1, res)
        return res

    def helper(self, nums, l, r, res):
        if l == r:
            res.append(nums[:]) # this will append unique combination
            res.append(nums) # this will result in a list full of same combinations
        else:
            for i in range(l, r + 1):
                nums[l], nums[i] = nums[i], nums[l]
                self.helper(nums, l + 1, r, res)
                nums[l], nums[i] = nums[i], nums[l]

Thanks for your help in advance!

Mitch
  • 3,342
  • 2
  • 21
  • 31
Yeonghun
  • 400
  • 5
  • 13
  • Go through this, same: https://stackoverflow.com/questions/35713891/what-is-the-meaning-of-arr-in-assignment-in-numpy and https://stackoverflow.com/questions/23440826/difference-between-arr-and-arr-in-python3-x – Pritish kumar Nov 05 '19 at 04:11
  • 2
    Generally speaking, `nums[:]` is equivalent to `nums.copy()`, which is what you should use nowadays if it's the behaviour you actually want. – Karl Knechtel Nov 05 '19 at 04:15

2 Answers2

6

nums[:] is a convenient way to make a shallow copy of a list in python. res.append(nums) appends a reference to nums, ie any changes to nums will also be reflected in res. res.append(nums[:]) will create a new copy of nums which you can change all you want without changing the original copy of nums

Hopefully this example makes it clear

nums = [1, 2, 3]
res = [nums]
res[0][0] = 'banana'
print(nums)

nums = [1, 2, 3]
res = [nums[:]]
res[0][0] = 'banana'
print(nums)

Gives the output

['banana', 2, 3]
[1, 2, 3]

Mitch
  • 3,342
  • 2
  • 21
  • 31
0

arr alone copies the pointer to the original list, whereas arr[:] creates a copy of arr.

When we make changes to the original array, the changes are reflected in the pointer, but not the copy:

>>> foo = [1, 2, 3]
>>> pointer = foo
>>> acopy = foo[:]
>>> foo[0] = 'banana'
>>> foo
['banana', 2, 3]
>>> pointer
['banana', 2, 3]
>>> acopy
[1, 2, 3]

If we make changes to the pointer, the changes are reflected in the original but not the copy:

>>> pointer[0] = 'chocolate'
>>> foo
['chocolate', 2, 3]
>>> pointer
['chocolate', 2, 3]
>>> acopy
[1, 2, 3]

If we make changes to the copy, the changes are isolated from the original and the pointer:

>>> acopy[0] = 'monkey'
>>> acopy
['monkey', 2, 3]
>>> foo
['chocolate', 2, 3]
>>> pointer
['chocolate', 2, 3]
John Mee
  • 50,179
  • 34
  • 152
  • 186