TypeError: can only concatenate list (not "tuple") to list

  • Thread starter Gabriel Genellina
  • Start date
G

Gabriel Genellina

Is there any reason for this error? Apart from "nobody cared to write the
code"

py> [1,2,3] + (4,5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "tuple") to list

In-place addition += does work:

py> a = [1,2,3]
py> a += (4,5)
py> a
[1, 2, 3, 4, 5]
 
S

Steven D'Aprano

Is there any reason for this error? Apart from "nobody cared to write
the code"

Yes, because such implicit conversions would be a bad idea.


py> [1,2,3] + (4,5)


What result are you expecting? A list or a tuple?


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


Apart from the different error message, this is essentially the same
error as this:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'


In-place addition += does work:

py> a = [1,2,3]
py> a += (4,5)
py> a
[1, 2, 3, 4, 5]


I call that an impressive gotcha. I believe that is because in-place
addition of lists is implemented as functionally equivalent to the extend
method:


a += "abc" # same as a.extend("abc")
a [1, 2, 3, 4, 5, 'a', 'b', 'c']
a += {None: -1}
a
[1, 2, 3, 4, 5, 'a', 'b', 'c', None]
 
G

Gabriel Genellina

En Mon, 04 Jan 2010 05:22:44 -0300, Steven D'Aprano
Yes, because such implicit conversions would be a bad idea.

I'm slowly convincing myself that it was actually a bad idea...
In-place addition += does work:

py> a = [1,2,3]
py> a += (4,5)
py> a
[1, 2, 3, 4, 5]

I call that an impressive gotcha. I believe that is because in-place
addition of lists is implemented as functionally equivalent to the extend
method:
a += "abc" # same as a.extend("abc")
a [1, 2, 3, 4, 5, 'a', 'b', 'c']
a += {None: -1}
a
[1, 2, 3, 4, 5, 'a', 'b', 'c', None]

So += and extend are completely permissive - they slurp whatever comes
from iterating their right operand. Totally unexpected in some cases, as
in your examples above...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top