Augmented Assignment question

Delaney, Timothy C (Timothy) tdelaney at avaya.com
Thu Jul 17 02:25:39 CEST 2003


> From: Doug Tolton [mailto:dtolton at 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





More information about the Python-list mailing list