3 ms·
> 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 [
by 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].