Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python list: append vs += [duplicate]

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.

like image 536
deltadu Avatar asked Jun 10 '26 05:06

deltadu


1 Answers

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

like image 90
Charles Landau Avatar answered Jun 11 '26 18:06

Charles Landau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!