Can you write Multilple Lines Lambda in Python?

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

Python return

Return outside function Python

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.