a question about list as an element in a tuple

Marko Rauhamaa marko at pacujo.net
Wed Feb 19 09:51:22 CET 2014


John O'Hagan <research at johnohagan.com>:

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

Nice catch! The += operator rebinds the reference even if the object
wouldn't change:

   >>> t = 1,
   >>> t[0] = t[0]
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   TypeError: 'tuple' object does not support item assignment

See also:

   >>> a = []
   >>> b = a
   >>> a = a + [1]
   >>> a is b
   False
   >>> a = []
   >>> b = a
   >>> a += [1]
   >>> a is b
   True

This behavior is not a bug, though. <URL:
http://docs.python.org/3.2/library/operator.html#inplace-operators>:

  for example, the statement x += y is equivalent to x =
  operator.iadd(x, y)

operator.iadd(x, y) modifies x in place and returns x. However, (<URL:
http://docs.python.org/3.2/library/operator.html#operator.add>) x + y is
dealt with by operator.add(x, y), which leaves x and y intact and must
return a new object.


Marko



More information about the Python-list mailing list