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]]