No, you cannot write multiple lines of lambda in Python. The lambda functions can have only one expression. One logical answer to this question is that if you want to write multiline functions, you should use regular functions in Python; why do you go for multiline lambdas?
Guido van Rossum (the creator of Python) answers this exact question in one of his blog post. So he admits that it’s theoretically possible, but the solution is not a Pythonic way to do that.
Even if you want to do it anyway, and then if you write, it becomes hideous, the solution is to make a braces expression.
Example 1
lambda: (
chaosWalking('tom'),
quitePlace(2),
blackWidow('SJ'))
This is an unpythonic way to write multiline lambda functions in Python.
However, you can achieve a multi-line lambda-like function using nested lambdas or logical expressions. Remember that these workarounds can make your code less readable and may not be recommended in all cases.
Example 2
Here’s an example using nested lambdas:
multi_line_lambda = (lambda x:
(lambda: x * 2)() if x > 0
else (lambda: x / 2)() if x < 0
else (lambda: x)()
)
print(multi_line_lambda(5))
print(multi_line_lambda(-5))
print(multi_line_lambda(0))
Output
10
-2.5
0
Related posts
Return outside function Python
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.