Skip to content Skip to sidebar Skip to footer

Does List Concatenation With The `+` Operator Always Return A New `list` Instance?

In Python, one can use the following to concatenate two lists into a new one: l1 = [0, 1, 2] l2 = [3, 4, 5] l3 = l1 + l2 I am looking for the language reference/documentation desc

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 as x = 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) or s += t | extends s with the contents of t (for the most part the same as s[len(s):len(s)] = t)


Solution 2:

[answer for a previous version of question: "where to look for docs"]

doc on +

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?"