Confused about passing by reference in this Python function -


i have simple python 2.7 function:

def sort_rows(mat):      mat = [sorted(i) in mat] 

however, when run:

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

i get

[[4, 5, 2, 8], [3, 9, 6, 7]] 

why wasn't m edited? thought python functions passed lists reference? missing something?

when sort_rows called mat points same list m points to. statement, however, changes that:

mat = [sorted(i) in mat] 

after above executed, mat points different list. m unchanged.

to change m in place:

>>> def sort_rows(mat):  ...     i, row in enumerate(mat): ...         mat[i] = sorted(row) ...  >>> sort_rows(m) >>> m [[2, 4, 5, 8], [3, 6, 7, 9]] 

the statement mat[i] = sorted(row) changes i-th element of mat not change list mat points to. hence, m changed also.

alternatively, can have function return list sorted rows:

>>> def rowsort(mat): ...     return [sorted(i) in mat] ...  >>> m = [[4, 5, 2, 8], [3, 9, 6, 7]] >>> m = rowsort(m) >>> m [[2, 4, 5, 8], [3, 6, 7, 9]] 

Comments