Python Lambda Functions

Python Lambda Functions are anonymous functions, which means they don’t have a name. The def keyword is used to define a typical function in Python, as we already know. The lambda keyword is also used in Python to define an anonymous function.

Syntax :

lambda arguments: expression

This function can have any number of arguments but only one expression, which is evaluated and returned.

Example :

string = 'codeinpocket'
print(lambda x:string)
Output : <function <lambda> at 0x000002509A413E20>

The print function does not call the lambda in this example; instead, it simply returns the function object and the memory location where it is stored.

So, in order for the print to print the string, we must first run the lambda function in order for the string to pass the print.

string = 'codeinpocket'

(lambda x : print(x))(string)
Output : codeinpocket

Difference Between Lambda functions and def defined function

Let’s understand this difference with example, here i am given 2 example first is return square of number using def and in second example pass the square of number using lambda function.

Example : Using def

def square(a):
    return a*a
print(square(5))
Output : 25

Example : Using lambda

lambda_fun = lambda x : x*x
print(lambda_fun(5))
Output : 25

Without using Lambda: Both of them return the square of a given number without using Lambda. However, we needed to declare a function with the name square and send a value to it while using def. We also needed to use the return keyword to return the result from where the function was called after it had been executed.
Using Lambda: Instead of a return statement, Lambda definitions always include an expression that is returned. We don’t have to assign a lambda definition to a variable because we can put it anywhere a function is expected. The beauty of lambda functions is their simplicity.

That is it for today, hope it helps.
If you have any suggestion for this article please make a comment in comment section below.

If you like this article, you can buy me a coffee. Thanks!

Python Lambda Functions

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top