3

I have the following code that breaks:

l = []
tup = ('a', 'b')
l = l + tup

which gives the below error

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "tuple") to list

but the below code runs

l = []
tup = ('a','b')
l += tup

without any error.

I always thought l+= is the same as l = l +

What is going on over here?

London guy
  • 27,522
  • 44
  • 121
  • 179
  • 2
    The first operation fails because it executes `l+tup` first which calls `__add__` which isn't supported, the latter calls `__iadd__` the implementation of which allows this so they are not implemented necessarily the same – EdChum Apr 24 '18 at 10:21

1 Answers1

1

The thing is that l = l + is calling list's __add__ method, whilst l += is calling __iadd__ method, which is addition in place (equivalent to calling extend method).

stasdeep
  • 2,758
  • 1
  • 16
  • 29