How to pass slice into a function by reference
<p>If I have</p>

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

def foo (arr):
    for i in len (arr): arr [i] += 1

def bar (arr):
    foo (arr[:2])

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

<p>I want output as </p>

<pre><code>&gt;&gt;&gt; [2, 3, 3 ]
</code></pre>

<p>How do I go about this?</p>

<p>Motivation: I want a priority queue where I can freeze last N elements, i.e. pass only queue[:N] to heapq.heappush() . But, every time I pass a slice, to it, or to any function in general, it sends a copy of slice and not the actual list to the function, and so my list remains unchanged in the end.</p>

<p><em>Slicing the list will create a new list with the sliced contents</em>, as such <code>arr[:2]</code> loses the reference to the original <code>a</code>.</p>

<p>Apart from that, iterating as you did won't change the list at all, it just changes an <code>item</code> and disregards the value.</p>

<p>If you want to alter specific parts of the list, you must carry with you a reference to the original list. For example, keep <code>arr</code>, iterate through a slice of it with <code>enumerate(arr[:2])</code> and then alter <code>arr</code>:</p>

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

def foo(arr):
    for i, item in enumerate(arr[:2]): 
        arr[i] = item + 1

def bar(arr):
    foo(arr)

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

<p>Printing now yields <code>[2, 3, 3]</code>, removing the slice in <code>enumerate</code> results in <code>[2, 3, 4]</code>.  Of course, <code>bar</code> here serves no purpose, you could drop it and just keep <code>foo</code> and call <code>foo(a)</code> immediately.</p>

python python-3.x pass-by-reference slice