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 yield
and getting confused.
Is there a proper legit way to achieve this in a loop?
Side note: yield
can be statement/expression depending on who you ask: yield - statement or expression?
Final Answer : yield can be used with lambda but the limitation(single-line) makes it useless. for/while
not possible in lambda because they are not expressions. -user2357112 implicit for loop is possible with list comprehension, and yield is valid within the list comprehension. -wim
Verdict- Explicit loops not possible because lambdas in python can only contain expressions, and to write an explicit loop you will need to use statements. -wim