Python Anonymous Function multiple lines

Here, we have discussed about Python Anonymous Function multiple lines or statements. We have learnt that in python, we can't write the multiple...

Python allows us to define a function in two ways i.e., one by using keyword and another by using keyword (known as anonymous function). 

Python Anonymous Function multiple lines

In this article we will learn about Python Anonymous Function multiple lines or statements.

But first, let's brush up your knowledge of Anonymous/Lambda Function in python.

Lambda function in python

A nameless function is anonymous function in python. Simply, A function declared without any name is called an anonymous function. The anonymous function is also called the Lambda function because these functions are declared by using the lambda keyword

lambda arguments: expression

Now let's understand this with the help of following example;

x = lambda a : a * a
print(x(12))

Output

144

If you check its lambda type then it will come back as a class function. To check the data type of a variable, use the function.

x = lambda a : a * a
print(type(x))

Output

<class 'function'>

Still the question arises whether we can write python anonymous function in multiple lines or not?

Python Anonymous Function Multiple Lines

In python, we can't write the multiple lines lambda function as it contains only one function. The creator of Python, Guido van Rossum, admits that in pythonic way it is not possible to write multiple lines lambda function as the lambda function are created to make the solution clean and convenient. But if anybody really wants to write multiline lambda in python, then it is possible in an unpythonic way. 

The solution to write multiline lambda function in python is to add a braces expression in parentheses.

 lambda: (

    Foo('xyz'),

    Bar(0),

    fun('abc'))

As we said that this is an unpythonic way of writing python Anonymous Function multiple lines. So generally, you should use the normal way of writing single line codes.

Conclusion

Above we have discussed about Python Anonymous Function multiple lines or statements. We have learnt that in python, we can't write the multiple lines lambda function as it contains only one function. But if anybody really wants to write multiline lambda in python, then it is possible in an unpythonic way.