In the below program, I am trying to add all my "new_list" values into my "fin_list". But append is not working as excpected and is overwriting it with whatever the "new_list"value is in that particular loop.
def all_subsequences(ind, a, new_list, fin_list):
if(ind >= len(a)):
print(new_list)
fin_list.append(new_list)
return
new_list.append(a[ind])
all_subsequences(ind+1, a, new_list, fin_list)
#new_list.remove(new_list[len(new_list)-1])
new_list.pop()
all_subsequences(ind+1, a, new_list, fin_list)
return fin_list
a = [3,1,2]
new_list = []
final_list = []
result = all_subsequences(0, a, new_list, final_list)
print(result)
Here the output at each level is as below
[3, 1, 2], [3, 1], [3, 2], [3], [1, 2], [1], [2], []
Since the last value is an empty list the final list value at the last is as below
[[], [], [], [], [], [], [], []]
Link to python sandbox :-
https://pythonsandbox.com/code/pythonsandbox_u21270_9PqNjYIsl7M85NGf4GBSLLrW_v0.py
I have tried to use extend instead of append inside the base condition but that is not the kind of result i am looking for. I am open to any suggestion to resolve this problem.
When you call
fin_list.append(new_list), you are appending the reference ofnew_listtofin_listinstead of copyingfin_list. Therefore, when you donew_list.pop()later, if you printfin_list, you will find it's also changed.The situation can be illustrated by this example:
The simplest way to solve the problem is to use
fin_list.append(new_list[:]), which will copynew_listand append the copy tofin_list.