简体   繁体   中英

Python incorrect ways to add to list when generating permutations

In this example, why does this generate the correct result:

nxt = path + [nums[i]]

But not:

nxt = path ; nxt += [nums[i]]
nxt = path ; nxt.append(nums[i])
def permute(nums):
    def dfs(nums, path):
      if not nums: # empty, done with path
          all_perms.append(path)
          return

      for i in range(len(nums)):
        nxt = path + [nums[i]]
        # nxt = path ; nxt += [nums[i]]
        # nxt = path ; nxt.append(nums[i])
        print(nxt)
        dfs(nums[:i] + nums[i+1:], nxt)

    all_perms = []
    dfs(nums, [])
    return all_perms

In this example, why does this generate the correct result:

 nxt = path + [nums[i]]

This leaves path unmodified.

But not:

 nxt = path ; nxt += [nums[i]]
 nxt = path ; nxt.append(nums[i])

This appends nums[i] to path which is apparently incorrect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM