Search code examples
python-3.xlistappendempty-list

Append Functionality in Python is not working as desired


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.


Solution

  • When you call fin_list.append(new_list), you are appending the reference of new_list to fin_list instead of copying fin_list. Therefore, when you do new_list.pop() later, if you print fin_list, you will find it's also changed.

    The situation can be illustrated by this example:

    foo = [1, 2, 3]
    bar = []
    bar.append(foo)
    print(f"bar: {bar}")
    
    # modify foo and you will find that bar is also modified
    foo.append(4)
    print(f"bar: {bar}")
    

    The simplest way to solve the problem is to use fin_list.append(new_list[:]), which will copy new_list and append the copy to fin_list.

    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.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)