Does List Concatenation With The `+` Operator Always Return A New `list` Instance?
Solution 1:
The reference documentation does not explicitly guarantee that :list + :list
results in a new list. However, it is implied by the +=
augmented assignment being explicitly in-place if possible in contrast to the +
operator.
The Python Language Reference: Augmented assignment statement
An augmented assignment expression like
x += 1
can be rewritten asx = x + 1
to achieve a similar, but not exactly equal effect. In the augmented version,x
is only evaluated once. Also, when possible, the actual operation is performed in-place, meaning that rather than creating a new object and assigning that to the target, the old object is modified instead.
The Python reference implementation CPython explicitly creates a new list on concatenation. Other compliant implementations can be expected to provide observably equivalent behaviour unless otherwise noted.
The list
type is documented to "implement all of the common and mutable sequence operations". These only guarantee that +=
extends mutable sequences inplace, and +
creates a new object for immutable sequences.
s + t
| the concatenation of s and t | (6)
(6) Concatenating immutable sequences always results in a new object. […]
s.extend(t)
ors += t
| extendss
with the contents oft
(for the most part the same ass[len(s):len(s)] = t
)
Solution 2:
[answer for a previous version of question: "where to look for docs"]
In Python +
and +=
are executed by calling __add__
and __iadd__
methods.
Unfortunately help([].__add__)
or help(list.__add__)
won't provide any useful doc.
Post a Comment for "Does List Concatenation With The `+` Operator Always Return A New `list` Instance?"