Confused about passing by reference in this Python function
<p>I have this simple Python 2.7 function:</p>

<pre><code>def sort_rows(mat): 
    mat = [sorted(i) for i in mat]
</code></pre>

<p>However, when I run: </p>

<pre><code>M = [[4, 5, 2, 8], [3, 9, 6, 7]]
sort_rows(M)
print(M)
</code></pre>

<p>I get</p>

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

<p>Why wasn't <code>M</code> edited? I thought python functions passed lists by reference? Am I missing something?</p>

<p>When your <code>sort_rows</code> is called <code>mat</code> points to the same list that <code>M</code> points to.  This statement, however, changes that:</p>

<pre><code>mat = [sorted(i) for i in mat]
</code></pre>

<p>After the above is executed, <code>mat</code> now points to a different list.  <code>M</code> is unchanged.</p>

<p>To change <code>M</code> in place:</p>

<pre><code>&gt;&gt;&gt; def sort_rows(mat): 
...     for i, row in enumerate(mat):
...         mat[i] = sorted(row)
... 
&gt;&gt;&gt; sort_rows(M)
&gt;&gt;&gt; M
[[2, 4, 5, 8], [3, 6, 7, 9]]
</code></pre>

<p>The statement <code>mat[i] = sorted(row)</code> changes the i-th element of <code>mat</code> but does not change the list that <code>mat</code> points to.  Hence, <code>M</code> is changed also.</p>

<p>Alternatively, you can have your function return a list with sorted rows:</p>

<pre><code>&gt;&gt;&gt; def rowsort(mat):
...     return [sorted(i) for i in mat]
... 
&gt;&gt;&gt; M = [[4, 5, 2, 8], [3, 9, 6, 7]]
&gt;&gt;&gt; M = rowsort(M)
&gt;&gt;&gt; M
[[2, 4, 5, 8], [3, 6, 7, 9]]
</code></pre>

python python-2.7