Python multiline lambda function | Example code

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))

Output:

Python multiline lambda function

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))

Source: stackoverflow.com

Do comment if you have any questions or suggestions on this Python lambda tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

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