Skip to content Skip to sidebar Skip to footer

Python Pass-by-value Vs. Pass-by-reference

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 obje

Solution 1:

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.

Solution 2:

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:

Python is call-by-value, not call-by-reference. See the wikipedia page on evaluation strategies.

As @ShashankGupta summarises: "Python is basically considered pass-by-value where all the values are references (since every name in a namespace is just a pointer to some object)." The view that python has some magical other evaluation strategy is the view of small subset of the python community who want python to be magical and unique. Python's way of dealing with objects+call-by-reference isn't even unique, and is present in (at least) Java, Smalltalk, and Ruby.

Also, your code does not show any calling/passing except passing databloc.

Solution 3:

There is no pass-by-reference or pass-by-value in Python (apart from implementation details – I'm talking about language properties). This kind of categorization just does not apply to Python at all. All there is are objects, who have type, identity (the hash) and data (a value).

The only difference between objects is if their data is mutable or immutable. I recommend reading the official documentation about Python's data model

Post a Comment for "Python Pass-by-value Vs. Pass-by-reference"