Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Python (http://www.velocityreviews.com/forums/f43-python.html)
-   -   RE: Augmented Assignment question (http://www.velocityreviews.com/forums/t319795-re-augmented-assignment-question.html)

 Delaney, Timothy C (Timothy) 07-17-2003 12:25 AM

RE: Augmented Assignment question

> From: Doug Tolton [mailto:dtolton@yahoo.com]
>
> I mis-spoke, lists are not included. You cannot do augmented
> assignments on tuples or multiple targets.

This is still incorrect. You correct thing to say is that you cannot do an augmented assignment on something which does not have a name, or which explicitly forbids it.

> >>> a,b = 0,0
> >>> a,b += 1,1

> SyntaxError: augmented assign to tuple not possible

>>> l = []
>>> l

[]
>>> id(l)

8289204
>>> l += [1,]
>>> l

[1]
>>> id(l)

8289204
>>> l += ['foo',]
>>> l

[1, 'foo']
>>> id(l)

8289204
>>> t = ()
>>> t

()
>>> id(t)

7966916
>>> t += (1,)
>>> t

(1,)
>>> id(t)

8261268
>>> t += ('foo',)
>>> t

(1, 'foo')
>>> id(t)

8133748

Note how the ID of `l` (list) does not change, but the id of `t` (tuple) does. This is because a tuple is immutable, and so:

t += (1,)

is equivalent to:

t = t + (1,)

whereas a list is mutable, and:

l += [1,]

is equivalent to:

l.extend([1,])

Every class can decide how to implement augmented assignment, using the __iadd__, etc magic methods.

Tim Delaney

 All times are GMT. The time now is 02:25 AM.