theMobDog theMobDog - 18 days ago 10
Python Question

python: lambda, yield-statement/expression and loops (Clarify)

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

My question is to clarify:

Whether the following simple loop function can be implemented with yield

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


Results in error:

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


Which looks like, it was expecting something as right operand for unwritten return statement but found the
yeild
and getting confused.

Is there a proper legit way to achieve this in a loop?

Side note:
yield
(generator obj) prefers expression that returns but you can also use a statement like
print()
as long as it is contained in a single line.

edit: Correction:
print()
is not a statement, but expression as someone pointed out.

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

As user2357112 pointed out, while yield can be used with lambda, the limitation of it makes it basically useless. No taker on loop question yet.(although it remains that limitation of lambda makes loop-implementation questionable)

wim wim
Answer

The one-liner you seem to be trying to create is actually technically possible with a lambda, you just need to help the parser a bit 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 uses a for loop implicitly in a list comprehension. It is not possible with an explicit while loop or for loop outside of a comprehension. That's because lambdas in python can only contain expressions, and to write an explicit loop you will need to use statements.

Comments