ShPavel ShPavel - 20 days ago 4
Python Question

Python, how to unroll tuples in lambda?

I have 2 equal-length lists and I am trying to get scalar product of them with, but it does not work this way:

sum(map(lambda a,b: a*b, zip(list1, list2)))

error: TypeError: <lambda>() takes exactly 2 arguments (1 given)


Even if this code is not good for my task, is there any way to force lambda to work with tuples for such cases?

i'd like to do something like

lambda x: (a,b)=x;a*b


But it will not work with C-style ';' )

Thank you for answers, still need to learn many things about Python )

Answer

well, you don't need a lambda for this...

sum(a*b for a, b in zip(list1, list2))

even zip() is slightly less than perfect... to avoid creating a list, either use python3, or itertools.izip:

sum(a*b for a, b in itertools.izip(list1, list2))

but if, for some craaaaazy reason, you really really wanted to use lambda, pass each list to map seperately:

sum(map(lambda a, b: a*b, list1, list2))

and even then, you didn't need a lambda either, a callable product is available in the operator module:

sum(map(operator.mul, list1, list2))

but use the generator in the first or second example, it will usually be faster.

Comments