python assignment

dan danbmil99 at yahoo.com
Thu Jul 24 22:25:36 EDT 2003


er, my example in last post should have been:

>>> for x in range(3):
...  for y in range(3):
...   temp[y] = x+y
...  v[x] = temp
...
>>> v
[[2, 3, 4], [2, 3, 4], [2, 3, 4]] #Surprise!  You're in Pythonville

#fixed:

>>> for x in range(3):
...  for y in range(3):
...   temp[y] = x+y
...  v[x] = temp + []
...
>>> v
[[0, 1, 2], [1, 2, 3], [2, 3, 4]] #expected behavior

but again the +[] looks funky in the morning light.  Can I always
assume that an operation of this sort will return a new object, even
if it has no effect on one of the operands?

I suppose a clearer fix would be v[x] = copy.copy(temp), eh?

"Tim Peters" <tim.one at comcast.net> wrote in message news:<mailman.1058992140.17079.python-list at python.org>...
> [Tim]
> >> It would be very unusual (because bad design) for the __iadd__
> >> method of a mutable type to return a pre-existing object, though.
> 
> [Juha Autero]
> > I'm confused. I thought that the idea of __iadd__ is that for
> > *mutable* types it modifies existing object instead of returning new
> > one.
> 
> Bjorn added more appropriate words -- it would be bad design for the
> __iadd__ method of a mutable type to return a pre-existing object other than
> self.
> 
> >>> a = [1, 2]
> >>> b = [1]
> >>> b += [2]
> 
> While "a == b" must be true at this point, it would be a nightmare if "a is
> b" could be true at this point.  For immutable types it doesn't matter:
> 
> >>> a = (1, 2)
> >>> b = (1,)
> >>> b += (2,)
> 
> It so happens that "a is b" is not true at this point under any Python
> released so far, but it could be true someday without causing harm.
> 
> Sorry for the confusion!




More information about the Python-list mailing list