python list: append vs += [duplicate]

≯℡__Kan透↙ 提交于 2020-12-21 03:48:54

问题


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:


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



来源:https://stackoverflow.com/questions/53112952/python-list-append-vs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!