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>Use a <em>list comprehension</em> and update the initial list using a full slice assignment with <code>[:]</code>:</p>

<pre><code>def foo(arr):
   arr[:] = [x+1 for x in arr]
</code></pre>

<p><em>Trial:</em></p>

<pre><code>&gt;&gt;&gt; a = [1, 2, 3]
&gt;&gt;&gt; def foo(arr):
...    arr[:] = [x+1 for x in arr]
...
&gt;&gt;&gt; foo(a)
&gt;&gt;&gt; a
[2, 3, 4]
</code></pre>

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