'Recursive function collects lists, but they are all the same

So the output i want should be something like this:

[[9],[9,8],[9,8,7]...[9,8,7,6,5,4,3,2,1]]

and this is the code that i am using:

a=[]
b=[]
i=0
def recur(i):
    i+=1
    if i<10:
        x=recur(i)
    else:
        return a
    b.append(i)
    a.append(b)
    return x
x=recur(i)

Please tell me what is wrong in this code that i am getting such a output like this:

[[9,8,7,...,1],[9,8,7,..1]....]


Solution 1:[1]

This happens because during the whole execution process there are only two lists a and b. There is no code that creates a third, fourth or more lists. It just mutates lists a and b.

For a that is fine, because that is the single list you will return to the caller (no matter that it gets the name x along the way, but that is just a synonym for a).

But for b it is problematic, because it gets appended to a repeatedly. Every time your code appends a value to it, this will be visible via a[0], via a[1], ...etc, since all these are synonyms for the list b.

To fix this, make a new list each time you want to append to a. Also avoid using global variables:

def recur(i):
    i += 1
    if i >= 9:
        return [[i]]
    
    a = recur(i)
    # Create a new(!) list based on the last one that was collected
    b = a[-1] + [i]
    a.append(b)
    return a


x=recur(0)

Now x will be:

[[9], [9, 8], [9, 8, 7], [9, 8, 7, 6], [9, 8, 7, 6, 5], [9, 8, 7, 6, 5, 4], [9, 8, 7, 6, 5, 4, 3], [9, 8, 7, 6, 5, 4, 3, 2], [9, 8, 7, 6, 5, 4, 3, 2, 1]]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1