0

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?

7 Answers 7

4

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])
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

3
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)

1 Comment

You answer is wrong, the sum can not accept there arguments.
1

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)

Comments

1

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

1 Comment

This is an example, I am trying to do something else but the lambda parameters are what I wanted to know about.
1
>>> g=lambda *l: sum(l)
>>> print g(1,2,3)
6

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.