0

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]....]
Evg
  • 25,259
  • 5
  • 41
  • 83

1 Answers1

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]]
trincot
  • 317,000
  • 35
  • 244
  • 286
  • but y is the value that is already appended to the list a changing? – gokussj4gt Feb 06 '22 at 06:48
  • There is no rule that says that something that is appended to a list cannot change. Just realise that there is only **one** `b` list in your code, not more. So whatever happens to `b` can be seen at all places where you have put a reference to it, like when the references in list `a` are all references to this same `b` list. – trincot Feb 06 '22 at 08:28