Can you write Multiline Lambda in Python?
No, you can’t write multiline lambda in Python because the lambda functions can have only one expression.
The creator of the Python programming language – Guido van Rossum, answered this question in one of his blogs. where he said that it’s theoretically possible, but the solution is not a Pythonic way to do that.
Python multiline lambda function
You can define your lambda on multiple lines if you put the expression in parentheses. This creates an implied line continuation, causing newlines to be ignored up to the closing parenthesis.
func = lambda a, b: ( b - a if a <= b else a * b ) print(func(10, 2))
You can also explicitly use the line continuation character “\”, but this is not the approach preferred by the Python style guide.
func = lambda a, b: \ b - a if a <= b else \ a * b print(func(10, 2))
Do comment if you have any questions or suggestions on this Python lambda tutorial.
Note: IDE: PyCharm 2021.1.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.