Reputation: 69
One of my function appends an item to the list. This appended list is then sent as argument into two recursive function. But when one of the called function updates its own local list, the original list gets modified because of which second recursive function gets modified list as input. Basically this is a sort of thing that i am trying to do. Here i want [2] [2,3] [2,4] as output but i am getting [2][2,3] as only output as the original list is getting modified. Is there any way that i can send same list in two functions.
def Growtree(llst, x):
if len(llst) == 2:
return
llst.append(x)
print(llst)
Growtree(llst,3)
Growtree(llst,4)
Upvotes: 0
Views: 89
Reputation: 5414
use copy.deepcopy()
The reason why the original list got modified in your functions, is that generally when you passing an mutable obj in python. It's the reference got passed into.
Upvotes: 0
Reputation: 2304
When Growtree(llst, 4)
is called there is already 2 and 3 in the list llst
. So it returns without appending a new element because of your if
.
What you need is to make a copy of the list (before to call Glowtree of inside, it depends if you want the orignal list to get modified).
To copy a list, see https://stackoverflow.com/a/2612815/3410584
Upvotes: 1