0

I am trying to traverse into a string using DFS and appending it to result in the line highlighted. However if I use result.append(currlist) vs result.append(currlist[:]), the result is totally different. The former doesn't work, why is that?

class Solution: 
       
    def dfs(self, start, s, currlist, result):
        if start >= len(s):
            result.append(currlist[:])  # <--
            return
        
        for end in range(start, len(s)):
            currlist.append(s[start:end+1])
            self.dfs(end+1, s, currlist, result)
            currlist.pop()
        
    def partition(self, s: str) -> List[List[str]]:
        result = []
        self.dfs(0, s, [], result)
        return result
wjandrea
  • 28,235
  • 9
  • 60
  • 81

1 Answers1

1

list[:] creates a copy of the object

Example:

x = []
y = [0, 1]

x.append(y)
print(x)

y[0] = 2

print(x)

Output:

[[0, 1]]
[[2, 1]]
x = []
y = [0, 1]

x.append(y[:])
print(x)

y[0] = 2

print(x)

Output:

[[0, 1]]
[[0, 1]]
Danis
  • 344
  • 2
  • 13