Python: lambda, yield-statement / expression and loop (Clarify)

TLDR: Can we implement yield or generator instruction (with a loop) within lambda ?

My question is to clarify:

Is it possible to implement the following simple loop function with output

 def loopyield(): for x in range(0,15): yield x print(*loopyield()) 

Error results:

 lamyield=lambda x: yield x for x in range(0,15) ^ SyntaxError: invalid syntax 

It looks like he was expecting something as the right operand for an unwritten return statement, but found yeild and got confused.

Is there a legal way to achieve this in a loop?

Side note: yield can be an expression / expression depending on who you ask: yield - statement or expression?

The final answer: income can be used with lambda, but the restriction (single line) makes it useless. for/while not possible in lambda because they are not expressions. -user2357112 implicit for the loop is possible with list comprehension, and profitability is valid in list comprehension. -wim

Verdict - Explicit loops are not possible because lambdas in python can only contain expressions, and you need operators to write an explicit loop. -wim

+19
python generator lambda loops
source share
3 answers

The only line you are trying to create is technically possible with a lambda, you just need to help the parser a little more:

 >>> lamyield = lambda: [(yield x) for x in range(15)] >>> print(*lamyield()) 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 

This implicitly uses the for loop in list comprehension. This is not possible with an explicit while or for loop beyond understanding. This is because lambda expressions in python can only contain expressions , and you need to use operators to write an explicit loop.

Note: this syntax is deprecated in Python 3.7 and will raise a SyntaxError in Python 3.8

+25
source share

Is there a need to use yield inside lambda if you can rewrite it with a generator to?

 In[1]: x = (i for i in range(15)) In[2]: x Out[2]: <generator object <genexpr> at 0x7fbdc69c3f10> In[3]: print(*x) Out[3]: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 In[4]: x = (i for i in range(0, 15)) In[5]: x.__next__() Out[5]: 0 In[6]: next(x) Out[6]: 1 
+5
source share

You can actually go through the lambda in useful ways, just the example you provided is not a good use case.

One example where you might want to use yield inside lambda might be to lazily execute expensive functions only when necessary. Like this:

 for check, args in (lambda: ( (yield (expensive_check1(), ["foo", "bar"])), (yield (expensive_check2(), ["baz"])), (yield (expensive_check3(), []), [])), ))(): if check: x = do_the_thing(*args) break else: raise Exception("oh noes!!!") 

* Note that this syntax will still work in Python 3.8, since it does not use yield inside the comprehension.

+1
source share

All Articles