Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #66677

Re: a question about list as an element in a tuple

From Marko Rauhamaa <marko@pacujo.net>
Newsgroups comp.lang.python
Subject Re: a question about list as an element in a tuple
Date 2014-02-19 10:51 +0200
Organization A noiseless patient Spider
Message-ID <87bny38oz9.fsf@elektro.pacujo.net> (permalink)
References <CAFysF+SirN1VKMhCcuWjLXkK--+V2Bxs4AbntJgTjcMDMhrWuA@mail.gmail.com> <mailman.7137.1392794077.18130.python-list@python.org>

Show all headers | View raw


John O'Hagan <research@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

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Re: a question about list as an element in a tuple John O'Hagan <research@johnohagan.com> - 2014-02-19 18:14 +1100
  Re: a question about list as an element in a tuple Marko Rauhamaa <marko@pacujo.net> - 2014-02-19 10:51 +0200
    Re: a question about list as an element in a tuple Marko Rauhamaa <marko@pacujo.net> - 2014-02-19 10:54 +0200

csiph-web