How to use a function to change a list when passed by reference?
<p>The code is passed an array. My understanding is this passing is done by reference. I want the function to recursively divide the last remaining half of the list in two and set each value that it was split at to zero.
The change to zero is happens in the array but when I call print a at the end I get the original array.</p>

<p>What am i doing wrong?</p>

<pre><code>a = range(10)

def listreduction(array):
    if len(array) == 1:
        array[0] = 0
        return

    split = len(array)/2
    array[split] = 0

    return listreduction(array[split:])

listreduction(a)
print a
</code></pre>

<p>The current output is </p>

<pre><code>[0, 1, 2, 3, 4, 0, 6, 7, 8, 9]
</code></pre>

<p>The should be more zeros to the right of the second one</p>

<p>In Python argumnet passing is different from other conventional programming language. arguments are passed by object reference. And the whether the referred object will be modifed or not it depends on two things</p>

<ul>
<li>Whether the variable is mutable or immutable. In your case <code>range</code> will create a list so its a mutable object. That implies that if you update <code>array</code> it should also update <code>a</code>. </li>
<li>Operation. <code>=</code> operation will always create new object reference. So even in your case <code>array</code> is mutable but since you are doing assignment operation It will create a new object reference. </li>
</ul>

<p>Following example should clear up the things for you. </p>

<p><strong>Example 1</strong></p>

<pre><code>  &gt;&gt;&gt; a = [1,2]
    def fun1(array):
        array= array + [3]
        print "var array = %s" %array

    fun1(a)
    print "var a = %s" %a
</code></pre>

<p><strong>Output</strong></p>

<pre><code>var array = [1, 2, 3]
var a = [1, 2]
</code></pre>

<p><strong>Example 2</strong></p>

<pre><code>a = [1,2]
def fun1(array):
    array.append(3)
    print "var array = %s" %array

fun1(a)
print "var a = %s" %a
</code></pre>

<p><strong>Output</strong></p>

<pre><code>var array = [1, 2, 3]
var a = [1, 2,3]
</code></pre>

python list