0

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)
ValLeNain
  • 2,232
  • 1
  • 18
  • 37
Carol
  • 69
  • 7
  • Please can you fix the indentation in your question? Also, `return` on its own will give you a `None` value. – roganjosh Mar 28 '17 at 20:48
  • You sure your indentation here is right? And perhaps define `llst` somewhere so others can try your code. – pvg Mar 28 '17 at 20:48
  • The function doesn't have "its own local list". Parameter passing doesn't make a copy in Python. See https://nedbatchelder.com/text/names.html – user2357112 Mar 28 '17 at 20:53

2 Answers2

1

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

Community
  • 1
  • 1
ValLeNain
  • 2,232
  • 1
  • 18
  • 37
0

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.

qichao_he
  • 4,204
  • 4
  • 15
  • 24