[Python-Dev] list += string??

Aahz aahz at pythoncraft.com
Thu Aug 26 16:23:25 CEST 2004


On Thu, Aug 26, 2004, David Abrahams wrote:
> 
> I just discovered the following behavior:
> 
>   C:\Documents and Settings\dave>python
>   Python 2.3 (#46, Aug 25 2003, 18:37:29) [MSC v.1200 32 bit (Intel)] on win32
>   Type "help", "copyright", "credits" or "license" for more information.
>   >>> prefix = ['foo', 'bar', 'baz']
>   >>> prefix += 'bomb'  # meant to write prefix += [ 'bomb' ]
>   >>> prefix
>   ['foo', 'bar', 'baz', 'b', 'o', 'm', 'b']
>   >>>
> 
> Is it new and/or intentional?  I would have expected an error from the
> +=.  I was very surprised when my error "passed silently".

>>> l = ['foo']
>>> l += ('bar', 'baz')
>>> l
['foo', 'bar', 'baz']

Augmented assignment for lists works with any sequence type (and
probably iterators, too, but I didn't check).  Strings are a sequence
type, which occasionally has unintended consequences.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

"To me vi is Zen.  To use vi is to practice zen.  Every command is a
koan.  Profound to the user, unintelligible to the uninitiated.  You
discover truth everytime you use it."  --reddy at lion.austin.ibm.com


More information about the Python-Dev mailing list