list*list

Ziga Seilnacht ziga.seilnacht at gmail.com
Mon May 1 19:24:04 EDT 2006


BBands wrote:
> There must be a better way to multiply the elements of one list by
> another:

[snipped]

> Perhaps a list comprehension or is this better addressed by NumPy?

If you have a large amount of numerical code, it is definetly better to
use numpy, since it is intended just for that purpose:

>>> import numpy
>>> a = numpy.array([1, 2, 3])
>>> b = numpy.array([1, 2, 3])
>>> c = a * b
>>> c
array([1, 4, 9])

Otherwise, you can use the builtin function map and functions in the
operator module:

>>> import operator
>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> c = map(operator.mul, a, b)
>>> c
[1, 4, 9]
>>> d = map(operator.add, a, b)
>>> d
[2, 4, 6]

> Thanks,
> 
>      jab

Ziga




More information about the Python-list mailing list