reference issue in python
Why is the assignment operator is not making a copy of the rvalue but a reference to that(on a list), and you have to use slices in order to make a real copy which creates an independent object so that changes on one does not affect the other. Is this related to some specific usage related the language that I missed until now?
Edit: what I understod is that in C++
int a = 1;
i开发者_Python百科nt b = a;
b = 2; // does not affect a
so I also thought that would be the same reasoning since Python is developed in C and it takes care of it with pointers most probably. With some simple code:
int a = 1;
/*int b = a;*/
int &b = a; /* what python does as I understood, if so why it does that this way?*/
is that more clear?
What I asked was more a comparison question on which I should be more clear, I agree ;-)
I recently posted an answer that discusses exactly this issue.
In python, everything can be considered as a reference. If you want an assignment to be a copy, you always need to put it excplicitely in your expression
a = range(10) # create a list and assign it to "a"
b = a # assign the object referenced by "a" to b
a is b # True --> a and b are two references to the same object. Works with any object
# after b = a
from copy import deepcopy
c = deepcopy(a) # or c = a[:] for lists
c is a # False
精彩评论