adding vectors

Mike Meyer mwm at mired.org
Mon Dec 19 23:25:06 EST 2005


Paul Rubin <http://phr.cx@NOSPAM.invalid> writes:

> Andy Leszczynski <yahoo at nospam.leszczynscy> writes:
>> Short question: why (1,"abc",0.3)+(2,"def",10.2) != (3,"abcdef",10.5)?
>> How to elegantly achieve (3,"abcdef",10.5) as a result of addition ...
> tuple([(a+b) for a,b in zip((1,"abc",0.3),(2,"def",10.2))])

>>> map(operator.add, (1, "abc", 0.3), (2, "def", 10.2))
[3, 'abcdef', 10.5]

Not having to do the zip is win. operator.add is a lose. I'm not sure
either is what I'd call elegant.

As for the "why" question, it's because the current behavior is more
generally useful. You can always concatenate two lists to get a longer
lists. The elements in a list don't have to support add, so using "+"
to denote elementwise addition is sorta pointless.

   <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list