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

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.

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)