a=([],); a[0]+=[1]

Mark 'Kamikaze' Hughes kamikaze at kuoi.asui.uidaho.edu
Wed May 5 16:18:18 EDT 2004


Andrea Griffini <agriff at tin.it>
wrote on Sat, 01 May 2004 15:18:16 GMT:
> When reading about python "warts" i stepped in this
> example I find quite puzzling:
>    a = ( [] , )
>    a[0] += [1]
> this gives an error, because a tuple cannot be
> modified. But if you print the content of "a"
> it will show it has indeed been modified.
> How can this happen ? if "+=" for list was called
> then no modification to the tuple was requested and
> so no error should have been raised; if instead "+"
> and "=" was executed then after a failing assignment
> the original list is safe... (or at least I thought
> so; if you type "a[0] = [2]" you get the error and
> "a" is not modified).
> Is there an explanation simpler than investigating
> on python sources ?

  First, as a matter of principle you probably shouldn't be modifying
the contents of a tuple, even if those contents are mutable.

  What you're seeing is that += is shorthand for "add, then store back
in the original container".  So it appends to the mutable list, then
tries to store that list back in the tuple, which fails.  Here's an
alternative:

Python 2.3.3 (#1, Mar 10 2004, 15:56:38)
[GCC 3.3.1 (SuSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a=([],)
>>> a
([],)
>>> a[0]
[]
>>> a[0].append(1)
>>> a
([1],)

  But see "First" above, and don't do this.  If you want the outer list
to be mutable, use a mutable list instead of a tuple.

-- 
 <a href="http://kuoi.asui.uidaho.edu/~kamikaze/"> Mark Hughes </a>
"Doing the impossible makes us mighty." -Captain Malcolm Reynolds, Firefly



More information about the Python-list mailing list