Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lambda arguments unpack error

In Python 2 this code is OK:

f = lambda (m, k): m + k

m = [1,2,3,4]
k = [5,6,7,8]

print(map(f, zip(m, k)))

but in Python 3 the following error occurred:

f = lambda (m, k): m + k
^
SyntaxError: invalid syntax

If I remove parentheses in lambda expression then another error occurred:

TypeError: <lambda>() missing 1 required positional argument: 'k'

Also approach with tuple as single lambda argument works in Python 3, but it's not clear (hard for reading):

f = lambda args: args[0] + args[1]

How can I unpack values in the right way in Python 3?

like image 498
mblw Avatar asked Jan 05 '15 08:01

mblw


People also ask

Is it possible to pass multiple arguments to a lambda expression?

Just like a normal function, a Lambda function can have multiple arguments with one expression.

How many arguments can lambda handle?

A lambda function can take any number of arguments, but can only have one expression.

What are lambdas coding?

Lambda expressions (or lambda functions) are essentially blocks of code that can be assigned to variables, passed as an argument, or returned from a function call, in languages that support high-order functions. They have been part of programming languages for quite some time.

Is lambda functional programming?

Lambda is the first concept introduced in Java and is the basis of the other concepts that functional programming brings in Java. Lambda expressions allow passing a function as an input parameter for another function, which was not possible earlier.


2 Answers

The removal of tuple unpacking is discussed in PEP 3113. Basically, you can't do this in Python 3. Under the headline Transition plan, you see that the "suggested" way of doing this is as your final code block:

lambda x_y: x_y[0] + x_y[1]
like image 118
vicvicvic Avatar answered Sep 16 '22 16:09

vicvicvic


You can use the same syntax in both Python 2 and Python 3 if you use itertools.starmap instead of map which unpacks the tuple items for us:

>>> from itertools import starmap
>>> f = lambda m, k: m + k
>>> list(starmap(f, zip(m, k)))
[6, 8, 10, 12]
like image 37
Ashwini Chaudhary Avatar answered Sep 19 '22 16:09

Ashwini Chaudhary