pythonpython-3.xlistappendmicrosoft-distributed-file-system

Python - What's different with "append(List)" and "append(List[ : ])"?


Here is the answer for LeetCode 39 problem, and I found it on github.

class Solution(object):
def combinationSum(self, candidates, target):

    self.resList = []
    candidates = sorted(candidates)
    self.dfs(candidates, [], target, 0)
    return self.resList

def dfs(self, candidates, sublist, target, last):
    if target == 0:
        // Change this line
        self.resList.append(sublist[:])
    if target < candidates[0]:
        return
    for n in candidates:
        if n > target:
            return
        if n < last:
            continue
        sublist.append(n)
        self.dfs(candidates, sublist, target - n, n)
        sublist.pop()

myClass = Solution()
result = myClass.combinationSum([2, 3, 5], 8)
print(result)

For this situation, the output is correct.

[[2, 2, 2, 2], [2, 3, 3], [3, 5]]

But if I change

...
self.resList.append(sublist[:])
...

to this

...
self.resList.append(sublist)
...

The output will be

[[], [], []]

I have no idea what's the different with "sublist" and "sublist[:]" here??


Solution

  • When you type:

    self.resList.append(sublist[:])
    

    Python is creating a new list object and appending a reference of the new list to resList.

    Alternatively, when you type:

    self.resList.append(sublist)
    

    Python does not create a new list and only appends a reference to sublist, so any changes that you make to sublist in the future will show in resList.

    A clearer way to code this would be:

    self.resList.append(list(sublist))