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.
1 Answer
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
+=concatenates, is more likeextend()rather thanappend().+=operator acts in-place on the left-hand operand. The+operator creates a new list from both operands, and neither is modified in place..appendaccepts 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)