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>To be honest instead of going for slice, I would just pass the indexes;</p>

<pre><code>a = [1, 2, 3]
def foo(array, start, stop, jmp= 1):
    for idx in range(start, stop + 1, jmp):
        array[idx] += 1

def bar(array):
    foo(array, 1, 2)
bar(a)
print(a)
[1, 3, 4]
</code></pre>

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