a question about list as an element in a tuple
John O'Hagan
research at johnohagan.com
Wed Feb 19 02:14:25 EST 2014
On Mon, 16 Dec 2013 11:30:13 +0800
liuerfire Wang <liuerfire at gmail.com> wrote:
> Just like below:
>
> In [1]: a = ([], [])
>
> In [2]: a[0].append(1)
>
> In [3]: a
> Out[3]: ([1], [])
>
> In [4]: a[0] += [1]
> ---------------------------------------------------------------------------
> TypeError Traceback (most recent call
> last) <ipython-input-4-ea29ca190a4d> in <module>()
> ----> 1 a[0] += [1]
>
> TypeError: 'tuple' object does not support item assignment
>
> In [5]: a
> Out[5]: ([1, 1], [])
>
> no problem, there is an exception. But a is still changed.
>
> is this a bug, or could anyone explain it?
>
> thanks.
>
This thread from two years ago deals with this in some detail:
https://mail.python.org/pipermail/python-list/2012-February/619265.html
It's one of those things that is hard to resolve in a way that makes
sense in every situation. The weirdest part for me is this:
>>> t = ([],)
>>> l = t[0]
>>> l is t[0]
True
>>> l += [1]
>>> t[0] += [1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
Whether there is an error or not depends on the name used for the
object!
--
John
More information about the Python-list
mailing list