Found interesting thing in Python (2.7) that never mentioned before.
This:
a = []
a += "a"
does work and result is:
>>> a
>>> ["a"]
But
a = []
a = a + "a"
gives
>>> TypeError: can only concatenate list (not "str") to list
Can someone explain why? Thanks for your answers.
Python distinguishes between the
+and+=operators and provides separate hooks for these;__add__and__iadd__. Thelist()type simply provides a different implementation for the latter.It is more efficient for lists to implement these separately;
__add__has to return a completely new list, while__iadd__can just extendselfthen returnself.In the C code,
__iadd__is implemented bylist_inplace_concat(), which simply callslistextend(), or, in python code,[].extend(). The latter takes any sequence, by design.The
__add__method on the other hand, represented in C bylist_concat, only takes alistas input, probably for efficiency’s sake; it can loop directly over the internal C array and copy items over to the new list.In conclusion, the reason
__iadd__accepts any sequence is because when PEP 203 (the Augmented Add proposal) was implemented, for lists it was simplest just to reuse the.extend()method.