Add vs in-place add of str to list

Erik Max Francis max at alcyone.com
Thu Oct 2 03:11:37 EDT 2008


rs387 wrote:

> I'm trying to understand why it is that I can do
> 
>>>> a = []
>>>> a += 'stuff'
>>>> a
> ['s', 't', 'u', 'f', 'f']
> 
> but not
> 
>>>> a = []
>>>> a = a + 'stuff'
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: can only concatenate list (not "str") to list
> 
> Can someone explain the logic? Why is the in-place add not a type
> error but the usual add is? (This applies to both Python 2.6rc1 and
> 3.0b2)

It's because the `+=` operator is doing the equivalent of calling the 
`extend` method, which treats its argument as a generic sequence, and 
doesn't enforce type.  The same thing happens with any other sequence 
type as the right-hand operand; for instance, tuples:

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

-- 
Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
  San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis
   Man is a hating rather than a loving animal.
    -- Rebecca West



More information about the Python-list mailing list