0

Can anyone explain what is happening here? When I append(l) to combs, combs = [[4,1]] and l=[3,2], so the expected result should be [[4,1],[3,2]] but instead it is [[3,2],[3,2]].

Also, if the same code is run with extend rather than append, then the result is aligned with the expected result.

def coin(n):
    l = [n]
    combs = []
    
    while l[0]>1:
        print(combs)
        if len(l)>1:
            l[1]+=1
            l[0]-=1
            combs.append(l)
        else:
            l.append(1)
            l[0]-=1
            combs.append(l)
   
    return combs

print(coin(5))

Output:

[]
[[4, 1]]
[[3, 2], [3, 2]]
[[2, 3], [2, 3], [2, 3]]

[[1, 4], [1, 4], [1, 4], [1, 4]]

Using combs.extend(l) instead than combs.append(l) Output:

[]
[4, 1]
[4, 1, 3, 2]
[4, 1, 3, 2, 2, 3]

[4, 1, 3, 2, 2, 3, 1, 4]
Yolao_21
  • 338
  • 2
  • 5
  • 1
    `combs` ends up containing multiple references to the same other list, `l`. When you mutate `l`, you can see the changes in `combs` because it contains `l`. – khelwood Mar 02 '22 at 11:16

0 Answers0