best way to do some simple tasks

Michael Hudson mwh at python.net
Thu Jan 30 13:20:03 CET 2003


Mike Meyer <mwm at mired.org> writes:

> Jp Calderone <exarkun at intarweb.us> writes:
> > On Wed, Jan 29, 2003 at 03:31:59PM -0800, Erik Lechak wrote:
> > > 3) What is the best way to do this?
> > > 
> > >    a=[1,2,3]
> > >    b=[1,1,1]
> > >    
> > >    how do I get c=a+b (c=[2,3,4])?
> > > 
> >      import operator
> >      c = map(operator.add, a, b)
> 
> You can save the import with a bit of extra ugliness:
> 
>         c = map(int.__add__, a, b)

But then you lose polymorphism:

>>> int.__add__(1.0, 2.0)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: descriptor '__add__' requires a 'int' object but received a 'float'

Cheers,
M.

-- 
  But since I'm not trying to impress  anybody in The Software Big
  Top, I'd rather walk the wire using a big pole, a safety harness,
  a net, and with the wire not more than 3 feet off the ground.
                                   -- Grant Griffin, comp.lang.python




More information about the Python-list mailing list