8

Why does this

l = [1,2,3]
l += 4,5,6

work, while this

l = [1,2,3] + (4,)

does not?

If I try the second one, I get a TypeError: can only concatenate list (not "tuple") to list, which makes sense.

But the first version should do about the same. In the second line the 4,5,6 should create a tuple, as seen in this example:

>>> t = 4,5,6
>>> type(t)
<type 'tuple'>

And after creating the tuple, += should just add to the list l. So also here it should throw some kind of error, but it does not.

Does anyone know what is happening here?

This behaviour is consistent between Python 2.7.11 and Python 3.5.1.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Dakkaron
  • 5,930
  • 2
  • 36
  • 51
  • 3
    In the words of [Tim Peters](http://stackoverflow.com/users/2705542/tim-peters), This is all intentional. Lists choose to implement `list += whatever` as a synonym for `list.extend(whatever)` - http://bugs.python.org/issue575536 – Bhargav Rao Jun 28 '16 at 15:13
  • That's pretty interesting, so you can extend whatever you want to a list, even if its a tuple. – RoadRunner Jun 28 '16 at 15:21
  • 1
    The concatenation and in-place concatenation of list are implemented in different ways in CPython. Here is a more detailed discussion: [If x is list, why does x += “ha” work, while x = x + “ha” throws an exception?](http://stackoverflow.com/questions/3216706/if-x-is-list-why-does-x-ha-work-while-x-x-ha-throws-an-exception) – sighingnow Jun 28 '16 at 15:22
  • 2
    @Kasramvad, This is a better dupe [Why does += behave unexpectedly on lists?](http://stackoverflow.com/q/2347265) imo. – Bhargav Rao Jun 28 '16 at 15:27

0 Answers0