Unexpected result for list operator "+="
Joe Smith
JoeSmith at bogusaddress.com
Thu Jan 4 20:47:52 EST 2001
I knew about mutable v. immutable. I just got surprised at the side effect. I
guess I have not used lists that much; otherwise, I would have probably used "L
= L1[:]" before. While it makes sense after realizing what is going on, I just
was surprised. Maybe I was thinking that it might copy on a change operation;
this way "L = L1; L += L2" really does the same thing as "L = L1 + L2".
(Including side effects.)
Greg Jorgensen wrote:
> Thanks to Fredrik, Alex, Tim, and Thomas for pointing out that Python only
> binds names to objects under the hood. I was guessing (maybe wrongly) that
> the original poster might not know about mutable and immutable objects,
> bindings, etc. That's why I wrote "Assignment of immutable objects
> essentially makes a copy of the object." I lifted the explanation almost
> verbatim from Beazley's "Python Essential Reference," page 19. Beazley wrote
> "... effectively creates a copy..." but it amounts to the same thing--a
> simplification. The real distinction--that assignment operations on
> immutable objects create new objects (or bind a reference to a different
> existing object)--is important but perhaps more information than necessary
> to answer the question.
>
> I appreciate the clarifications and detailed implementation info.
More information about the Python-list
mailing list