3 ms·
Hum, I wouldn't for objects that are generally passed by reference (which is an early lesson one should learn with Python). Eg. a = [1, 2] b = [3, 4] c = a
by necovek 5y ago
Hum, I wouldn't for objects that are generally passed by reference (which is an early lesson one should learn with Python).
Eg.
a = [1, 2]
b = [3, 4]
c = a
Would you really expect a += b and a = a + b to behave the same, and what would c be in that case?
- thaumasiotes 5y ago> Would you really expect a += b and a = a + b to behave the same, and what would c be in that case? Yes, I would, and it really is worth noting that they don't. c would be [1,2,3,4], and it would be an alias of a. But both of those points are also true of the way things actually do work. I don't really understand your question.
- alisonkisk 5y agoreassigning a does not change c. a = [1] c = a a = a + a Now, what is c ? what is a? Then try again with a+=a
- account42 5y ago>>> a = [1, 2] >>> b = [3, 4] >>> c = a >>> a = a + b >>> c [1, 2]
- necovek 5y ago> But both of those points are also true of the way things actually do work. That is not true. >>> a = [1, 2] >>> b = [3, 4] >>> c = a >>> a += b >>> c [1, 2, 3, 4] And contrast that with: >>> a = [1, 2] >>> b = [3, 4] >>> c = a >>> a = a + b >>> c [1, 2] If "c" remains an alias of "a" after you've assigned something else to "a", then there is no way in language to keep a reference to what "a" was. Eg. what you seem to be proposing is that assignment works like this: a = 4 old_a = a a = 5 print(old_a) # prints out 5. Python is like it is for practical performance reasons: lists and dicts are by-reference because copying them is expensive. You've got to do it explicitely with .copy() or deepcopy module. That's a basic lesson on Python I was referring to. And sure, it could have been designed the other way around, when you'd have to introduce a "refcopy" or "&" operator when performance is needed, but it wasn't designed that way. There are other languages which do that. I can see the point of "a += b" unexpectedly updating in place, but just upon reading it, I'd struggle to figure out what's supposed to happen. In a code review, I'd suggest a developer to switch to "a.extend(b)". Basically, if they were to behave the same, I don't think an argument can be made for the common result of "c" to evaluate to [1, 2, 3, 4], but rather to [1, 2].