I wrote a Python function to reverse a nested list:
def ReverseList(inputlist,parent=[]):
if len(inputlist)==0:
tem_out=parent[:]
return tem_out
else:
next_i=inputlist[-1]
if type(next_i) == list:
parent.append(ReverseList(next_i,[]))
else:
parent.append(next_i)
temp_par=parent[:]
return ReverseList(inputlist[:-1],temp_par)
print(ReverseList([1,2,[11,22],3,5]))
print(ReverseList([1,2,[11,22],3,5]))
print(ReverseList([1,2,[11,22],3,5]))
print(ReverseList([1,2,[11,22],3,5]))
In the last 4 lines I repetitively called the same function with the same input. It gives following output:
[5, 3, [22, 11], 2, 1]
[5, 5, 3, [22, 11], 2, 1]
[5, 5, 5, 3, [22, 11], 2, 1]
[5, 5, 5, 5, 3, [22, 11], 2, 1]
Only in the first output shows the correct answer.
And I tried to do this without using default arguments, which gives the correct answer
def ReverseList_no_default_arg(inputlist,parent):
if len(inputlist)==0:
tem_out=parent[:]
return tem_out
else:
next_i=inputlist[-1]
if type(next_i) == list:
parent.append(ReverseList_no_default_arg(next_i,[]))
else:
parent.append(next_i)
temp_par=parent[:]
return ReverseList_no_default_arg(inputlist[:-1],temp_par)
print(ReverseList_no_default_arg([1,2,[11,22],3,5],[]))
print(ReverseList_no_default_arg([1,2,[11,22],3,5],[]))
print(ReverseList_no_default_arg([1,2,[11,22],3,5],[]))
print(ReverseList_no_default_arg([1,2,[11,22],3,5],[]))
Which gives this as output
[5, 3, [22, 11], 2, 1]
[5, 3, [22, 11], 2, 1]
[5, 3, [22, 11], 2, 1]
[5, 3, [22, 11], 2, 1]
What is the reason behind this difference?