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>Since you use recursion, the slice operation in the argument will create new list instance which is different than you instance. That's the reason.</p>

<p>You can change your code as following:</p>

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

def list_reduction(array, position=0):
    if len(array) -1 &lt;= position:
        return

    split = position + (len(array) - position) / 2
    array[split] = 0
    return list_reduction(array, split)

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

<p>The output is:</p>

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

python list