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

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon Jan 4 10:39:45 CET 2010


En Mon, 04 Jan 2010 05:22:44 -0300, Steven D'Aprano  
<steven at remove.this.cybersource.com.au> escribió:

> 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.

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...

-- 
Gabriel Genellina




More information about the Python-list mailing list