adding vectors

Alex Martelli aleax at
Mon Dec 19 23:35:26 EST 2005

Andy Leszczynski <yahoo at nospam.leszczynscy> wrote:

> Hi,
> Short question: why (1,"abc",0.3)+(2,"def",10.2) != (3,"abcdef",10.5)?

Because '+' applied to sequences means to concatenate them -- a more
frequent need than "element by element addition" (which I notice you
would NOT want to apply to strings, only to sequences for which it
happens to be convenient for your specific app...!-).

> How to elegantly achieve (3,"abcdef",10.5) as a result of addition ...

If you mean "by using operator + on tuples", no way.  If you're not hung
up on syntax, e.g.

def elemadd(t1, t2):
  return tuple(i1+i2 for i1, i2 in zip(t1, t2))

or any of several other ways.


More information about the Python-list mailing list