Yesterday, I posted about what seemed to be a Python inconsistency. Basically, we were puzzled as to why Python would allow:
l = [1, 2, 3]
t = (4, 5, 6)
l += (4,)but would generate an error with:
l = [1, 2, 3]
t = (4, 5, 6)
l = l + (4,)One of the former TAs for 6.00 pointed out that there are two parts to consider. The first is that we shouldn't assume
__add__ (implements +) and __iadd__ (implements +=) have the same semantics. __iadd__ is supposed to actually modify the object in place. __add__ doesn't have that stipulation. Python has a fall back behavior where if it can't find
__iadd__ implemented for a particular object, then it will try to use __add__, however, for lists __iadd__ is overridden so that it functions like extend().The second point to consider is in the following bit of code:
l = [1,2,3]
t = (4,5,6)
l = l + tThe expression
l + t should evaluate to a value. What should the type be? tuple or list? It's ambiguous. Whereas:l = [1,2,3]
t = (4,5,6)
l += tIn
l += t, __iadd__ knows that it's modifying a list in place, so it can take appropriate action with a tuple argument. __iadd__ for tuples isn't implemented because tuples are immutable.Dilemma resolved.