Still one of the oldest #Python oddities I've ever seen 🐍🤔
>>> a = ([],)
>>> a[0] += ["what"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> a
(['what'],)
Note that an exception was raised but the operation also worked! 😳 #pythonoddity
@treyhunner Ha! That's a good one, it really illustrates how `+=` is just syntactic sugar over the `+` and the `=`
@chris @treyhunner @s_gruppetta
It's weirder than that!
`a[0] = a[0] + ["what"]` reports the error but doesn't have the side effect.
`a[0] += ["what"]` reports the error and DOES have the side effect!
I'm shocked both that the failed assignment has a side effect and that these do not behave the same way. Can anyone explain?
@treyhunner @chris @s_gruppetta Ah, that explains it!
Definitely still odd.
@peterdrake @chris @s_gruppetta right!
I usually explain to my students by noting that __iadd__ stands for in-place addition and in-place operations are intended to mutate the original object when possible.
Though += and friends are most often used on strings and numbers, which are immutable so we don't see that behavior most of the time...
I do wonder whether it might have been more sensible to design Python to never mutate with augmented assignments, even on mutable objects.
@peterdrake @chris @s_gruppetta though this issue comes up so rarely it may not even be worth considering "what if they'd designed things differently" 🤷
Almost any time I might use += on a list, I tend to use the extend method instead because += on a list does the same thing as the list extend method anyway.
@treyhunner @chris @s_gruppetta I presume this feature was added so that programmers wouldn't have to think about the most efficient way of extending a list.
In the corner, the functional programming people are smugly examining their cuticles.
@undefined @treyhunner @chris @s_gruppetta This has implications beyond tuples. If `a` is a list and we
`b = a`
then
`a = a + ...`
does not modify `b` but
`a += ...`
does.