Amish Gupta
Amish Gupta

Reputation: 151

Unexpected behaviour of append

l="??"
ans=[]
g=list(l)
def allcombination(x):
    for i in range(len(x)):
        if x[i]=='?':
            x[i]='A'
            allcombination((x))
            ans.append(list(x))           #the problem is in this line, changing list(x) to x gives a different answer.
            x[i]='B'
            allcombination((x))
            ans.append(list(x))           #the problem is in this line, changing list(x) to x gives a different answer
            return
allcombination(g)
print(ans)

The output is: [['A', 'A'], ['A', 'B'], ['A', 'B'], ['B', 'B']]

l="??"
ans=[]
g=list(l)
def allcombination(x):
    for i in range(len(x)):
        if x[i]=='?':
            x[i]='A'
            allcombination((x))         #the problem is in this line
            ans.append((x))
            x[i]='B'
            allcombination((x))         #the problem is in this line
            ans.append((x))
            return
allcombination(g)
print(ans)

The output is: [['B', 'B'], ['B', 'B'], ['B', 'B'], ['B', 'B']]

Ignore what the code is about, why the difference in output? Please give solution and the detailed reason. Incase you are curious, the below code gives the desired output:

l="??"
ans=[]
g=list(l)
def allcombination(x):
    for i in range(len(x)):
        if x[i]=='?':
            x[i]='A'
            allcombination(list(x))
            x[i]='B'
            allcombination(list(x))
            return
    ans.append(list(x))        #ans.append((x)) will NOT give the right answer, Idk why.
allcombination(g)
print(ans)

The output is: [['A', 'A'], ['A', 'B'], ['B', 'A'], ['B', 'B']]

The comments in the codes above point out the problem. How does it matter if I use, list(x) or x, I have even printed the type(x), it is of the type list.

Upvotes: 1

Views: 56

Answers (1)

azro
azro

Reputation: 54168

Appending with ans.append(x) does the add the x list, that one instance, then if you modify it, you'll see in there too, as it points to it

A simple example to show that

a = [1, 2, 3]
b = [a]
print(b)  # [[1, 2, 3]]

a[0] = 6
print(b)  # [[6, 2, 3]]

Whereas ans.append(list(x)) does copy x, then you have saved in ans a list with the values of x, not not x itself, that allows you do continue using x

Upvotes: 2

Related Questions