1

I tried looping in a lambda function, and my code is:

zxm=lambda k:[k+x for x in range(k)]
print(zxm(5))

and the output which I got is when I gave the input:

[5,6,7,8,9]

My expected output is however the sum of all the 5 numbers and I want:

35

How can we loop in lambda? Also, is there a chance of recursion in one?

martineau
  • 99,260
  • 22
  • 139
  • 249

2 Answers2

7

That's not a loop per se, it's a list comprehension. You can use sum to get the sum, for example.

In [7]: zxm = lambda k: sum(k+x for x in range(k))

In [8]: zxm(5)
Out[8]: 35

Note that statements like for are forbidden inside lambda; only expressions are permitted, so while you can use list comprehensions you cannot write a traditional for loop.

Eli Bendersky
  • 231,995
  • 78
  • 333
  • 394
  • 1
    Note that this solution used a generator comprehension (`()`) rather than a list comprehension (`[]`) which can be more efficient (especially if the list is big). More info: http://stackoverflow.com/questions/47789/generator-expressions-vs-list-comprehension – Oliver Dain Dec 29 '16 at 20:57
1

First, there is sum method in python. You can just do sum(zxm(5)). Recursive lambdas do exists (see: Y Combinator), and this is possible in python (see Can a lambda function call itself recursively in Python?), however, the practicality of this is not particularly strong. Lambdas can be looped (over lists) inside of as you have done here. The issue is not that zxm is a lambda but the way it is defined. You can get the sum in zxm by defining it as such zxm=lambda k: sum([k+x for x in range(k)]).

Community
  • 1
  • 1
Eli Sadoff
  • 6,628
  • 6
  • 29
  • 54