TypeError: can only concatenate list (not "tuple") to list
Steven D'Aprano
steven at REMOVE.THIS.cybersource.com.au
Mon Jan 4 03:22:44 EST 2010
On Mon, 04 Jan 2010 04:59:02 -0300, Gabriel Genellina wrote:
> 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:
>>> 2 + "2"
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]
--
Steven
More information about the Python-list
mailing list