Augmented Assignment question
Bengt Richter
bokr at oz.net
Thu Jul 17 01:38:05 EDT 2003
On Wed, 16 Jul 2003 22:17:40 GMT, Doug Tolton <dtolton at yahoo.com> wrote:
>On 16 Jul 2003 16:51:38 -0400, aahz at pythoncraft.com (Aahz) wrote:
>
>>In article <215bhv0bnkn13eivh0s64ic5ml8obpgfg7 at 4ax.com>,
>>Doug Tolton <dtolton at yahoo.com> wrote:
>>>
>>>I did some reading and it seems that an augmented assignment is
>>>specifically verboten on tuples and lists. Is there a clean way to
>>>accomplish this?
>>
>>Really?
>>
>>>>> l = []
>>>>> l+=[1]
>>>>> l
>>[1]
>>>>> l+=['foo']
>>>>> l
>>[1, 'foo']
>
>
>I mis-spoke, lists are not included. You cannot do augmented
>assignments on tuples or multiple targets.
>
>you can do what you typed, but you can't do.
>
>>>> a,b = 0,0
>>>> a,b += 1,1
>SyntaxError: augmented assign to tuple not possible
>
>or this:
>
>>>> a,b = [],[]
>>>> a,b += [1],[1]
>SyntaxError: augmented assign to tuple not possible
>
>That is specifically the point I was getting at. Forgive the
>technical slip of including lists in the discussion.
>
A little experiment (not tested beyond what you see ;-):
>>> class TX(tuple):
... def __add__(self, other):
... return TX([s+o for s,o in zip(self, other)])
...
>>> tx = TX((2,2))
>>> tx
(2, 2)
>>> tx + (3,5)
(5, 7)
>>> tx
(2, 2)
>>> tx += (3,5)
>>> tx
(5, 7)
>>> tx += 10,20
>>> tx
(15, 27)
>>> tt = TX(('ab','cd','ef'))
>>> tt
('ab', 'cd', 'ef')
>>> tt += '123'
>>> tt
('ab1', 'cd2', 'ef3')
Regards,
Bengt Richter
More information about the Python-list
mailing list