AppDividend
Latest Code Tutorials

Can you write Multilple Lines Lambda in Python?

0

In Python, you can define the normal functions using the def keyword and lambda functions using the lambda keyword. You can use the Lambda functions wherever function objects are required.

What is the Python lambda function?

Python lambda is just another method to define a function with one difference is that it is generally a one-line function. Lambda functions can have zero or more arguments but it has only one expression.

The lambda function in Python is also called an anonymous function because it is defined without a name.

Syntax

lambda arguments: expression

The return value of the lambda function is the value that this expression is evaluated to.

Example

fun = lambda x: x * x
print(fun(3))

Output

9

If you check the type of lambda, then it returns a class function. To check the data type of a variable, use the type() function.

fun = lambda x: x * x

print(type(fun))

Output

<class 'function'>

Now, a million-dollar question is can you write a multiple lines lambda function in Python? Let’s discuss that.

Can you write Python lambda multiple lines?

No, you can not write multiple lines lambda in Python. The lambda functions can have only one expression. 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.

One logical answer to this question is that if you want to write multiline functions, then you should use regular functions in Python; why you go for multiline lambdas.

Even you want to do it anyway, and then if you write, it becomes very ugly, so the solution is to make a braces expression.

lambda: (
    chaosWalking('tom'),
    quitePlace(2),
    blackWidow('SJ'))

This is literally an unpythonic way to write multiline lambda functions in Python.

The lambda function is created so that you can conveniently write short solutions. In general, you are better off using a normal function definition if it becomes anything beyond one line of simple code.

That is it for Python multiple lines lambda function tutorial.

Leave A Reply

Your email address will not be published.

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