I have the following code:
g = lambda a, b, c: sum(a, b, c)
print g([4,6,7])
How do I get the lambda function to expand the list into 3 values?
g = lambda L: sum(L)
print g([4,6,7])
would work for any arbitrarily sized list.
If you want to use g = lambda a, b, c: someFunc(a, b, c), then call print g(4,6,7)
sum can not accept there arguments.The code you are looking for is:
>>> g = lambda a, b, c: sum([a, b, c])
>>> print g(*[4,6,7])
17
What you were trying to do wont work:
>>> g = lambda a, b, c: sum(a, b, c)
>>> print g(*[4,6,7])
Traceback (most recent call last):
File "<pyshell#83>", line 1, in <module>
print g(*[4,6,7])
File "<pyshell#82>", line 1, in <lambda>
g = lambda a, b, c: sum(a, b, c)
TypeError: sum expected at most 2 arguments, got 3
Because sum() can't handle the arguments you gave it.
Since your lambda function is simply a sum() function, why not just call sum() directly?
If your code the following a, b, c values:
>>> a, b, c = range(1,4)
>>> print a,b,c
1 2 3
And you wanted to do:
>>> g = lambda a, b, c: sum([a, b, c])
>>> print g(*[a,b,c])
6
Why not just do the following?:
>>> sum([a,b,c])
6
If your lambda expects to have a list/tuple of fixed length passed in, but wants to expand the values in that list/tuple into separate parameter variables, the following will work.
g = lambda (a, b, c): a + b + c
g([4, 6, 7])
Note the parentheses around the parameter list.
This "feature" works in Python 2.x, but was removed in Python 3