Idiomatic Python for incrementing pairs

Jason Swails jason.swails at gmail.com
Sat Jun 8 07:37:25 EDT 2013


On Sat, Jun 8, 2013 at 2:47 AM, Peter Otten <__peter__ at web.de> wrote:
>
> You can hide the complexity in a custom class:
>
> >>> class T(tuple):
> ...     def __add__(self, other):
> ...             return T((a+b) for a, b in zip(self, other))
> ...
> >>> t = T((0, 0))
> >>> for pair in [(1, 10), (2, 20), (3, 30)]:
> ...     t += pair
> ...
> >>> t
> (6, 60)
>
> (If you are already using numpy you can do the above with a numpy.array
> instead of writing your own T.)
>

I do this frequently when I want data structures that behave like vectors
but don't want to impose the numpy dependency on users. (Although I usually
inherit from a mutable sequence so I can override __iadd__ and __isub__).
It seemed overkill for the provided example, though...

All the best,
Jason
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20130608/acbbdff4/attachment.html>


More information about the Python-list mailing list