[Tutor] multiply and sum two lists with list comprehension?
Kent Johnson
kent37 at tds.net
Thu Jan 28 14:38:31 CET 2010
On Thu, Jan 28, 2010 at 1:22 AM, Muhammad Ali <ali.jan at gmail.com> wrote:
>
> Hi,
>
> I am multipliying two lists so that each of list As elements get multiplied
> to the corresponding list Bs. Then I am summing the product.
>
> For example, A= [1, 2, 3] and B=[2, 2, 2] so that I get [2, 4, 6] after
> multiplication and then sum it to get 12. I can do it using map like this:
>
> sum(map(lambda i,j:i*j, A, B))
You don't need a lambda, use operator.mul():
sum(map(operator.mul, A, B))
Kent
More information about the Tutor
mailing list