Anonymous functions

There are functions which don’t have name. To create an anonymous function you use the lambda keyword instead of def.

The following program statement creates an anonymous function that computes the cube of its argument


In the above example, lambda x:x*3 is a anonymous function, x is an argument and x*3 is the body of the function.

Let’s create a simple function and then try to convert it into an anonymous function.
def person_details(first_name, last_name):
full_name = first_name.strip().title() + " " + last_name.strip().title()

print("Full_name is:", full_name)
person_details('david', 'smith')

Here, you are defining a normal function with def keyword with parameters as first_name and last_name. The strip( ) is used to remove the leading and trailing whitespaces in your string, the title( ) is used to capitalize the first letter in each string(review the string module for better understanding.) and its returning the string values as:

Full_name is: David Smith

Now, we will convert the above function into anonymous function using lambda keyword:

full_name = lambda fn, ln: fn.strip().title() + " " + ln.strip().title()
print("Full_name is:", full_name('david', 'smith'))

As you can see, there is no function, we just declared a variable with name full_name and assigning it a lambda function which converts the first word capitalized from the given string. And finally we are passing the values or parameters into full_name which is completely working as above mentioned persons_details function and providing output as:

Full_name is: David Smith

Complete and Continue