Khalil carsten
Khalil carsten

Reputation: 13

Python list append different lists in the same scope for the same variable

Okay. I write an algorithm for show me all the permutations of a list of integers. But during the algorithm I got a problem to append a permuted list to my result list.

The code is the heap's algorithm. I got my finished permutation when size == 1. So a can append the permutated list V to my final list res. Here's the code:

The function for permutate the list

def permutations(V, size):
    global res

    if size == 1:
        print(V)
        res.append(V)

    for i in range(0, size):
        permutations(V, size-1)

        if size % 2 == 1:
            V[size-1], V[0] = V[0], V[size-1]
        else:
            V[i], V[size-1] = V[size-1], V[i]

A = [1,2,3]
res = []
permutation(A, len(A))
print(res)

And this is the output:

[1, 2, 3]
[2, 1, 3]
[3, 1, 2]
[1, 3, 2]
[2, 3, 1]
[3, 2, 1]
res: [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]

The printed permutations of V are all correct. But the list V append to my global res are not change. They are being append right after the print and the list append is different.

If you change the lines like this:

res.append(V)
  |
  |
  v      
D = [V[i] for i in range(len(V))]
res.append(D)

The results is correct on the final. Anyone can explain how can a printed list can be different from a appended list using the same variable.

Upvotes: 0

Views: 25

Answers (1)

Shawn Luo
Shawn Luo

Reputation: 36

Replace res.append(V) with res.append(list(V)) simply fixes your issue.

All V you appended to the res are references to the same object. This can be observed by printing the id of each element in the list:

for i in res:
    print(id(i))

Upvotes: 1

Related Questions