0

The python docs imply that s.extend(t) and s += t are equivalent for some mutable sequence s and iterable t. I'm surprised to find that they are not equivalent for an immutable sequence. Can someone shed some light on why extend raises an error

>>> s = (1, 2)
>>> s.extend((3,))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'extend'

but += does not

>>> s = (1, 2)
>>> s += (3,)
>>> s
(1, 2, 3)

Is there a practical reason why extend can't create a new tuple the way += does?

John Cole
  • 153
  • 1
  • 8
  • I think you misunderstood the error. Tuple's do not have a method `extend`. That is why you can't call it, not because it can't create a new tuple, but because that is not a method for tuple's. – Chrispresso Mar 09 '20 at 16:00
  • Tuple isn't a *mutable* type, so none of the stuff in the documentation about mutable sequence types applies. So then the answer lies in what `+=` falls back to when the class doesn't implement `__iadd__`… – deceze Mar 09 '20 at 16:02
  • @Chrispresso I get that, but if += is equivalent to extend for mutable objects, and immutable objects support +=, why don't they also support extend? It appears extend is intentionally undefined for tuples. If there is a good reason not to define it, why should += be allowed? – John Cole Mar 09 '20 at 21:04
  • @deceze do you know where I can find what += falls back to for tuples? – John Cole Mar 09 '20 at 21:07
  • Read the duplicates…? And to answer your question from above: `.extend` on an immutable type would be somewhere between very misleading and nonsensical. – deceze Mar 09 '20 at 21:24
  • @deceze Thanks, I have read the duplicates (and a lot more besides). What helped me the most was the top answer to [this question](https://stackoverflow.com/questions/2347265/why-does-behave-unexpectedly-on-lists?noredirect=1&lq=1) linked in a comment from one of the marked duplicates. – John Cole Mar 10 '20 at 00:38

0 Answers0