user3254780 user3254780 - 7 months ago 7
Python Question

Why won't the lists be appended to my global list?

I wrote the following code, used to generate all possible combinations of a specific number of elements with help of recursion:

global_values = []
parameters = [1,2,3,4,5,6]
content = ["x","y","v","sd"]

def rec(values, depth):
if(depth == 0):
global_values.append(values)
print values
return

for i in range(0,len(parameters)):
values.append(parameters[i])
rec(values,depth-1)
values.pop()
return

rec([],len(content))

print "!!!!----------!!!!"
print global_values


The "print "value"" statement prints the correct results, but I would like to append this results to the global list. Why doesn't this work?

With

parameters = [1,2,3]
content = ["x","y"]


I get the output:

[1, 1]
[1, 2]
[1, 3]
[2, 1]
[2, 2]
[2, 3]
[3, 1]
[3, 2]
[3, 3]
!!!!----------!!!!
[[], [], [], [], [], [], [], [], []]


But I want the last list filled with the values printed before.

Answer

At the time you append values to global_values, there are numbers in the list values. However, you remove those numbers later, and and thus the list that was appended to global_values is now empty. This problem happens because there is only ever one list values that keeps getting re-used.

To see what I mean try:

list1 = []
list2 = [5,9]
list1.append(list2)
list2.pop() #because list2 is inside list1, this changes the contents of list1
print list1 #prints [[5]]

To append a copy of values use global_values.append(values[:])