Python: passing parameters over functions
<p>Python Experts,</p>

<p>I have been trying to implement BST using Python and here is my code for the insert function:</p>

<p><strong>Draft 1:</strong></p>

<pre><code>def insert(self, val):
    newNode = self._Node(val)

    if (self._root is None):
        self._root = newNode
    else:
        self._insert(self._root,val)

def _insert(self, node, val):

    if node is None:
        node = self._Node(val)

    elif val &gt;= node._val:

        self._insert(node._right, val)
    else:
        self._insert(node._left, val)
</code></pre>

<p>But, I'm unable to construct the tree except the root. I'm guessing I messed up somewhere with the parameters passing over the two functions because when I modify the code as below, I get it alright:</p>

<p><strong>Draft 2:</strong></p>

<pre><code>def insert(self, val):
    newNode = self._Node(val)

    if (self._root is None):
        self._root = newNode
    else:
        self._insert(self._root,val)

def _insert(self, node, val):

    if val &gt;= node._val:
        if node._right is None:
                node._right = self._Node(val)
        else:
                self._insert(node._right, val)
    else:
        if node._left is None:
                node._left = self._Node(val)
        else:
                self._insert(node._left, val)
</code></pre>

<p>I'm trying hard to understand why the draft 2 works but draft 1 doesn't. Any help here? Thanks in advance!</p>

<p>I believe this is due to the fact that by doing :</p>

<pre><code>node = self._Node(val) 
</code></pre>

<p>in the _insert function you are not changing the value of the left/right node but binding the name node to a new _Node object, thus letting the left/right node as None. </p>

<p>On your second draft you are effectively affecting a new object to left / right node.</p>

<p>Here's a simple example to illustrate what happens on your code.</p>

<p>Guess what the print(test) will display?</p>

<pre><code>test = [5, 5, 5]

def function(list):
   list[0] = 10
   list = range(1, 3)

function(test)
print test
</code></pre>

<p>If you think it will display [1,2] you're wrong .. it will actually display [10, 5, 5] because when doing list = range(1, 3) we are binding the name list to another object and not changing the first object it was bound to (the one test is actually bound to)</p>

python