Given this code:
sumThree = lambda (x, y, z): (x[0]+ y[0] + z[0], x[1] + y[1] + z[1])
print 'sumThree((1, 2), (3, 4), (5, 6)) = {0}'.format(sumThree((1, 2), (3, 4), (5, 6)))
I get:
TypeError Traceback (most recent call last)
<ipython-input-43-7f1b9571e230> in <module>()
16 # second position summed. E.g. (1, 2), (3, 4), (5, 6) => (1 + 3 + 5, 2 + 4 + 6) => (9, 12)
17 sumThree = lambda (x0, x1, x2): (x[0]+ y[0] + z[0], x[1] + y[1] + z[1])
---> 18 print 'sumThree((1, 2), (3, 4), (5, 6)) = {0}'.format(sumThree((1, 2), (3, 4), (5, 6)))
TypeError: <lambda>() takes exactly 1 argument (3 given)
And the question is of course, why?
You can either remove the brackets around the lambda arguments:
sumThree = lambda x, y, z: (x[0]+ y[0] + z[0], x[1] + y[1] + z[1])
or otherwise pass the arguments as a single tuple to the original lambda:
print 'sumThree((1, 2), (3, 4), (5, 6)) = {0}'.format(sumThree(((1, 2), (3, 4), (5, 6))))
You made a lambda function which takes one argument: the tuple (x, y, z). If you call your function with a tuple as its sole argument, it will work:
sumThree(((1, 2), (3, 4), (5, 6)))
Alternatively, you can re-write the lambda function to not take one tuple argument, but three arguments:
sumThree = lambda (x, y, z): (x[0]+ y[0] + z[0], x[1] + y[1] + z[1])
Note also that it's good coding practice to simply define named functions (i.e. def sumThree(x, y, z):
). Using a lambda function and assigning it to a variable (sumThree) defeats the only advantage that lambdas have over regular functions: that you don't need to shove them into a variable.
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