I can't understand pass by reference and pass by value method in python while passing objects. Please Help. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

I can't understand pass by reference and pass by value method in python while passing objects. Please Help.

I am from c++ background. Pass by value and pass by reference are pretty clear in c++ because of &operator but in python I am confused how to pass object so that I can change the original object when necessary.

22nd May 2018, 2:28 AM
ankush_953
12 Answers
+ 1
import copy class node: def __init__(self,data=None): self.data = copy.deepcopy(data) #copy self.next = None def append(self, data): if self.data == None: self.data = copy.deepcopy(data) return temp = self while temp.next != None: temp = temp.next temp.next = node(data) def traverse(self): temp = self while temp: print(temp.data) temp = temp.next root = node() root.append(4) root.append(9) root.traverse()
22nd May 2018, 11:10 AM
Disvolviĝo;
Disvolviĝo; - avatar
+ 1
In python all is passed by reference. But there is difference between immutable types and mutable ones. After passed if the IMMUTABLE type variable is changed, it is copied automatically. So the variable looks as if it were passed by value. About MUTABLE type, it isn't copied. So it is only passed by reference.
22nd May 2018, 4:57 AM
Disvolviĝo;
Disvolviĝo; - avatar
+ 1
thank you but are user defined objects mutable or immutable ?
22nd May 2018, 5:39 AM
ankush_953
+ 1
Immutable: int, float, str, tuple, bytes, frozenset Mutable : list, dict, set, bytearray
22nd May 2018, 5:41 AM
Disvolviĝo;
Disvolviĝo; - avatar
+ 1
But in which category user defined classes fall in ? Mutable or immutable ?
22nd May 2018, 5:43 AM
ankush_953
+ 1
It is mutable
22nd May 2018, 5:45 AM
Disvolviĝo;
Disvolviĝo; - avatar
+ 1
https://code.sololearn.com/cm2wP8FcgrcV/?ref=app But here root doesn't get changed in append function. why ?
22nd May 2018, 5:55 AM
ankush_953
+ 1
Python : def append(root, data) | | v c++ : void append(node *root, int data) the root behaves as a pointer
22nd May 2018, 6:00 AM
Disvolviĝo;
Disvolviĝo; - avatar
+ 1
I use double pointer in c++ . void append(node **root,int data) hence returning value was not my headache any more. so I didn't need to return values. So is there something I can do in python ?
22nd May 2018, 6:03 AM
ankush_953
+ 1
Why don't you add the function to the class node.
22nd May 2018, 6:09 AM
Disvolviĝo;
Disvolviĝo; - avatar
+ 1
Because I get confused when Value gets changed and when it doesn't... That's Why I did it by this method but here also mutability failed as per my knowledge. :(
22nd May 2018, 6:16 AM
ankush_953
+ 1
Thank you so much for your help. :)
22nd May 2018, 11:21 AM
ankush_953