In Python, lambda functions are typically one line functions. It is possible to write multiple line lambda functions with “” after each line, however is not truly pythonic.

lambda_expression = lambda x: True if x > 0 
                                                     else False

If you need more than 1 line for a function, it is better to define your own function.

def customFunction(x):
    if x > 0:
        return True
    else:
        return False

In Python, lambda expressions are very useful for creating anonymous functions which can be applied on variables or collections of objects.

When using lambda functions in Python, we need to understand that the lambda construct is limited to expressions only.

Therefore, to use lambda expressions in their intended form, we are limited to one line.

However, it is possible to define a lambda expression with multiple lines since we can always use “” to go to the next line in our Python code.

Below is an example of a multiple line lambda expression in Python.

lambda_expression = lambda x: True if x > 0 
                                                     else False

However, in this case, it would have been just as easy to write the lambda as:

lambda_expression = lambda x: True if x > 0 else False

If you have a lot of logic or conditionals to check in your code, our recommendation is to define your own function and then use that function.

Hopefully this article has helped you understand how to work with lambda expressions and why it might not be the best idea to use a multiple line lambda in Python.

Categorized in:

Python,

Last Update: February 26, 2024