Sunday, 29 May 2016

Python : When is a variable passed by reference and when by value?












My code :



locs = [ [1], [2] ]
for loc in locs:
loc = []

print locs
# prints => [ [1], [2] ]



Why is loc not reference of elements of locs ?



Python : Everything is passed as reference unless explicitly copied [ Is this not True ? ]



Please explain.. how does python decides referencing and copying ?



Update :



How to do ?




def compute(ob):
if isinstance(ob,list): return process_list(ob)
if isinstance(ob,dict): return process_dict(ob)

for loc in locs:
loc = compute(loc) # What to change here to make loc a reference of actual locs iteration ?



  • locs must contain the final processed response !


  • I don't want to use enumerate, is it possible without it ?


Answer



Everything in Python is passed and assigned by value, in the same way that everything is passed and assigned by value in Java. Every value in Python is a reference (pointer) to an object. Objects cannot be values. Assignment always copies the value (which is a pointer); two such pointers can thus point to the same object. Objects are never copied unless you're doing something explicit to copy them.



For your case, every iteration of the loop assigns an element of the list into the variable loc. You then assign something else to the variable loc. All these values are pointers; you're assigning pointers; but you do not affect any objects in any way.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...