user5679590
user5679590

Reputation:

Can looping be done in a lambda?

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?

Upvotes: 1

Views: 291

Answers (2)

Eli Sadoff
Eli Sadoff

Reputation: 7308

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)]).

Upvotes: 1

Eli Bendersky
Eli Bendersky

Reputation: 273416

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.

Upvotes: 7

Related Questions