smac89
smac89

Reputation: 43147

Python lambda parameters

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?

Upvotes: 0

Views: 931

Answers (7)

Sean
Sean

Reputation: 4515

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

Upvotes: 1

zhangyangyu
zhangyangyu

Reputation: 8610

Expand the list t0 3 values can be done by this:

 g(*[4,6,7])

But the sum won't work in your way. Or you can write this way:

>>> g = lambda *arg: sum(arg)
>>> print g(4, 5, 6)
15
>>> 

Or just make your lambda accept a list:

g = lambda alist: sum(alist)
print g([4,6,7])

Upvotes: 4

inspectorG4dget
inspectorG4dget

Reputation: 114005

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)

Upvotes: 3

Rohit Jain
Rohit Jain

Reputation: 213281

Why can't you change lambda to take a list. Because sum() doesn't take three arguments:

>>> g = lambda a_list: sum(a_list)
>>> print g([4,6,7])
17

or a non-keyword argument:

>>> g = lambda *nkwargs: sum(nkwargs)
>>> print g(4,6,7)
17

Upvotes: 3

Frodon
Frodon

Reputation: 3775

>>> g=lambda *l: sum(l)
>>> print g(1,2,3)
6

Upvotes: 1

Inbar Rose
Inbar Rose

Reputation: 43457

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

Upvotes: 1

Jon Kiparsky
Jon Kiparsky

Reputation: 7753

You're defining a function which takes three parameters, and the supplying it with a single parameter, a list. If you want

print g([4,6,7])

to work, your definition should be

g = lambda lst: sum(lst)

Upvotes: 1

Related Questions