[Tutor] Unexpected behavior of +=
Michael Broe
mbroe at columbus.rr.com
Wed Feb 15 23:45:48 CET 2006
I just discovered the following behavior, but can't find any
documentation about it:
>>> list = []
>>> list = list + 'abc'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: can only concatenate list (not "str") to list
but:
>>> list = []
>>> list += 'abc'
>>> list
['a', 'b', 'c']
Is this a special characteristic that has been added to the augmented
assignment operator +=; or is it an automatic consequence of +=
assignment being performed'in place'? (Tho I can't see how it could
be...)
It just seems very un-Pythonesque to be able to successfully
concatenate objects of different types like this. And it seems very
inconsistent with standard assignment.
Indeed, the Python Reference Manual, section 6.3.1 states:
"With the exception of assigning to tuples and multiple targets in a
single statement, the assignment done by augmented assignment
statements is handled the same way as normal assignments. Similarly,
with the exception of the possible in-place behavior, the binary
operation performed by augmented assignment is the same as the normal
binary operations."
...which is patently not the case here.
I was scandalized lol!
More information about the Tutor
mailing list