New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
List inplace addition different from normal addition #89456
Comments
Hi, I tried addition and in-place addition on a list.
>>> l += 'de'
>>> print(l)
['a', 'b' , 'c', 'd', 'e'] I want to ask why the behaviour of both these are different?? If it is done intentionally, then it should be there in the documentation but I am not able to find any reference. |
For those not in front of a computer, the error is: >>> l = l + 'de'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "str") to list |
https://docs.python.org/3/faq/programming.html#faq-augmented-assignment-tuple-error
This example is calling extend on list of strings with another string as argument. Hence the target string is iterated and each character is added as an element. __add__ is different compared __iadd__. For += __iadd__ is called if defined and falls back to __add__ |
Kapil, this behavior was intentional (not a bug), but later regarded as a design mistake. GvR has said that if he had to do it over again list.__iadd__ would only accept other lists. The problem arises when people write "somelist += 'hello'" and expect it to add a single string with one word rather than five one letter strings. That said, the current behavior is guaranteed, people rely on it, and we cannot change it. As Karthikeyan points out, this is documented. However since the docs have grown so voluminous, it is often difficult to find any one particular fact. |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: