[Tutor] multiply and sum two lists with list comprehension?
ghartshaw at gmail.com
Thu Jan 28 07:44:00 CET 2010
> 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))
> But map is being dropped out in python 3? or has it already been dropped?
It appears to still work in 3.1.1. I don't know if it is going to be
> And I have heard Guido say that list comprehension do a better job than
> map so how would we do this with list comps?
This should be equivalent.
Python 3.1.1+ (r311:74480, Nov 2 2009, 15:45:00)
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> [i*j for i,j in zip(A,B)]
[2, 4, 6]
>>> sum([i*j for i,j in zip(A,B)])
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Tutor