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.

3
  • 7
    They don't do the same thing. += concatenates, is more like extend() rather than append(). Commented Nov 2, 2018 at 5:10
  • they are not the same, see duplicates for details. Commented Nov 2, 2018 at 6: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) Commented Nov 2, 2018 at 6:32

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.