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

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Mon Jan 4 04:45:46 EST 2010


On Mon, 04 Jan 2010 06:27:48 -0300, Gabriel Genellina wrote:

> En Mon, 04 Jan 2010 05:24:56 -0300, David Williams
> <david at bibliolabs.com> escribió:
> 
>>> 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]
>>
>> I guess to expand a bit more on what I said...  What should the result
>> be?
>>  A list or a tuple?  The reason += works is because the end result is
>> clear; a list.  But it is ambiguous in the case of concatenation: did
>> you want a tuple or a list?
> 
> Uhm... it seems "obvious" to me that [1,2,3] + (4,5) should be
> [1,2,3,4,5]. A list. That's what I would expect, although I cannot
> explain why is it *so* obvious to me.

If you can't explain it, it's probably a bad idea. Why should lists be 
privileged over tuples?

How does it work? Do tuples automatically turn into lists, or does the 
left hand value over-ride the right hand value?

In other words, would you expect:


"1" + 1 = "11"
1 + "1" = 2

or would you expect:


"1" + 1 = "11"
1 + "1" = "11"




> Given that 2 + 3.5, and 'abc' + u'def' both return an instance of their
> right operand's type, I should probably revise my preconceptions...

Yes, you should be a little more careful in your tests.


>>> 2 + 3.5
5.5
>>> 3.5 + 2
5.5


Nothing to do with left versus right.



-- 
Steven



More information about the Python-list mailing list