0

In Python3, let me define simple a list and tuple as follows:

In [1]: alist = [1, 2, 3]
In [2]: atuple = (4, 5, 6)

If I attempt an "add" (+) of the tuple to the list and assign that to the original list I get a TyperError:

In [3]: alist = alist + atuple
TypeError: can only concatenate list (not "tuple") to list`

However, if I use the augmented assignment operator, it will append atuple to alist, it will work as intended:

In [4]: alist += atuple
In [5]: alist
Out[5]: [1, 2, 3, 4, 5, 6]

So, logically, why does the augmented assignment operator work, In [4], while the long form, In [3], throws are Error?

I want to understand why the augmented assignment operation allows appending a tuple to a list while the + operator does not.

  • _So, logically, why does the augmented assignment operator work_ Because under the hood, they actually have different behavior. See the dupe question link. – John Gordon Aug 26 '23 at 16:04
  • Yes, I see that works. To me logically alist = alist + atuple should work as well. Apparently the __add__ magic method for the list class doesn't allow other iterable types to be added (concatenated). – Lee McNally Aug 26 '23 at 16:12

0 Answers0