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

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.