Re:Why Do Python Lists Multiply Oddly? Exploring the CPython...
by flaghacker on Tuesday April 09, 2024 @03:58AM
(#39977096)
Matlab is one language that chooses the second. Every assignment a=b where b is a matrix creates a distinct copy of the matrix.
The interpreter is slightly more clever and instead implements this as a copy-on-writr mechanism, but that's just an implementation detail .
Re:Why Do Python Lists Multiply Oddly? Exploring the CPython...
by Someone on Tuesday April 09, 2024 @04:01AM
(#39977116)
> If you say it’s the second (I can’t think of any language that does), then `a = […]; b = a` is an expensive copy by value assignment
In Swift collections are value types, so b = a conceptually is a copy. It’s not expensive, though, because Swift does copy-on-write.
You pay for that by a combination of having more expensive collection updates (they, at least conceptually, have to check whether to make that copy) and a more complex compiler (it tries to avoid having to actually do those checks at runtime)
var a: [Int]=[]
var b = [a,a,a,a]
b[0].append(1)
print(b)
will produce [[1],[],[],[]]
> In more sane languages, the expression [] means give me an empty list value, nothing more and nothing less
What is a “list value”? It’s either a pointer to some other space where the lists values are stored, or it’s the values stored themselves. If you say it’s the second (I can’t think of any language that does), then `a = […]; b = a` is an expensive copy by value assignment. Is that worth that trade off to get less surprising results in the articles case? I’m not saying the answer is “obviously no”, but it definitely isn’t “obviously yes”.