3 ms·
This one is an odd one because initially most people I show this one to assume the oddity is that immutable types cannot be mutated in-place. But tuples can be
by th 9y ago
This one is an odd one because initially most people I show this one to assume the oddity is that immutable types cannot be mutated in-place.
But tuples can be mutated in-place:
>>> b = (1,)
>>> b += (2,)
>>> b
(1, 2)
The odd thing is that lists can be in-place added (+='d) to any iterable, while tuples can only be in-place added to tuples.
I think it works this way so that += on lists works consistently with the extend method on lists, which also accepts any iterable.
- masklinn 9y ago> But tuples can be mutated in-place: >>> b = (1,) >>> b += (2,) >>> b (1, 2) That's not an in-place mutation any more than >>> a = 1 >>> a += 2 is. The oddity is that most people assume `a += b` is the same as `a = a + b`, but Python allows overloading both separately and list.__iadd__ is an alias for list.extend, hence being able to += any iterable onto a list whereas `list + non_list` generates a type error. The original intent is an optimisation (to avoid copying the subject list) but it's a broken one as it behaves very inconsistently with regular concatenation/addition: it mutates the subject in-place and allows a different (wider) set of parameters.