Python 2.7 – Python Pass-by-Value vs. Pass-by-Reference

pythonpython-2.7

I thought I understood python's pass-by-reference processing… Why is there a difference between pass-by-reference for lists vs. that for list elements, specially if both are objects as far as I understand it:

 dataBloc = [ ['123'] , ['345'] ]

 print dataBloc

 def func( b ):
     print ( 'Row-by-Row Before' , b )
     for row in b:
         row = [ float(x) for x in row ]
     print ( 'Row-by-Row After' , b )

     print ( 'Element-by-Element Before' , b )
     for row in b:
         for i in range(len(row)):
             row[i] = float(row[i])
     print ( 'Element-by-Element After' , b )

     return b

 print func(dataBloc)

 [['123'], ['345']]
 ('Row-by-Row Before', [['123'], ['345']])
 ('Row-by-Row After', [['123'], ['345']])
 ('Element-by-Element Before', [['123'], ['345']])
 ('Element-by-Element After', [[123.0], [345.0]])
 [[123.0], [345.0]]

Thanks.

Best Answer

Firstly, this question has nothing to do with either pass-by-value or pass-by-reference, because you're not doing any passing, you're simply mutating values within a function.

Secondly, there is no such difference. The difference is in your code: you are doing different things. In the first loop, you assign each element in the list to the name 'row'. Then, you reassign the name 'row' to point to something else. The actual value that was previously in 'row' is unchanged, so of course the original list is itself unchanged, since you didn't actually change the contents.

In the second, inside each row you specifically mutate the contents of each element via its index. So, the list is changed.

Related Question