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>The reason is that the <code>sorted</code> function doesn't sort the list in place, if you want it be sorted in place, you can use <code>list.sort()</code> method:</p>

<pre><code>def sort_rows(mat): 
    [i.sort() for i in mat]

M = [[4, 5, 2, 8], [3, 9, 6, 7]]
sort_rows(M)
print(M)

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

<p><code>sorted</code> returns a new list but the original list doesn't change:</p>

<pre><code>x = [3, 2, 1, 4]

sorted(x)
# [1, 2, 3, 4]

x
# [3, 2, 1, 4]                  # x doesn't change here
</code></pre>

python python-2.7