3

For Python list, is append() the same as +=? I know that + will lead to the creation of a new list, while append() just append new stuff to the old list. But will += be optimized to be more similar to append()? since they do the same thing.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
deltadu
  • 49
  • 1
  • 4
  • 7
    They don't do the same thing. `+=` concatenates, is more like `extend()` rather than `append()`. – Julien Nov 02 '18 at 05:10
  • they are not the same, see duplicates for details. – Vaibhav Vishal Nov 02 '18 at 06:30
  • the `+=` operator acts *in-place* on the left-hand operand. The `+` operator creates a *new list* from both operands, and neither is modified in place. `.append` accepts a *single element* which it appends to the end of the list. So, `+=` acts like `.extend` (and probably calls the same function under the hood) – juanpa.arrivillaga Nov 02 '18 at 06:32

1 Answers1

1

It's an __iadd__ operator. Docs.

Importantly, this means that it only tries to append. "For instance, if x is an instance of a class with an __iadd__() method, x += y is equivalent to x = x.__iadd__(y) . Otherwise, x.__add__(y) and y.__radd__(x) are considered, as with the evaluation of x + y."

This thread specifically deals with lists and their iadd behavior

Charles Landau
  • 4,187
  • 1
  • 8
  • 24