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?
Just like a normal function, a Lambda function can have multiple arguments with one expression.
A lambda function can take any number of arguments, but can only have one expression.
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.
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.
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]
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With