Python Anonymous or Lambda Functions

Python Anonymous or Lambda Functions, What is an Anonymous Function, Why it is called Lambda Functions, Advantages of Lambda, What is Not a Disadvantage

What is an Anonymous Function?

Anonymous Function is a function defined without a name.

It will not be defined with the keyword “def”. It could be used in-line.

There are a few anonymous functions available in Python, each one can help in different scenarios. Let’s see one by one.

Why it is called Lambda Functions?

In python, the Syntax to create an Anonymous Function uses a keyword “lambda”. So it is also called as lambda function.

Syntax:

lambda arguments: expression

Example: lambda x: x*2

Rules:

Any number of arguments can be used in lambda function.

There should be only one expression. The result of the expression will be returned.

No return statements.

Use of Lambda Functions:

  • Lambda functions are inline functions without a name, and so it is an Anonymous Function.
  • We can use lambda functions when we require a nameless function for a short period of time.
  • As these functions are inline, we can use this as to have inline operations where there is already a complex function and we need a call to another one-line functions. Example: An complex expression as an argument to a higher-order function. In other words, a function that takes in other functions as arguments.
  • Lambda functions are used along with built-in functions like filter(), map() etc.
  • Lambda functions can have any number of arguments but only one expression. The expression is evaluated and returned.

Why Lambda? Advantages:

Memory efficient, reduce the code complexity

Not a Disadvantage:

When thinking about Lambda, we can say there is No code reusability. But this is not a disadvantage. The main use of Lambda function is to use only when we require a nameless function for a short period of time.

#Square function
x = 10
result = (lambda x: x*x)
print(result(10))
100

Here you can see that the variable x will act as a placeholder to receive the argument passed to the function. The expression of the function will be made using this variable.

As lambda is a function, we can call the function using the variable to which it was returned.

Using other functions with Lambda:

We can construct the expression of lamba function using another function. It can be either user defined or a built-in function.

Lets write a function to clean the text to remove empty spaces and convert it to lower case.

def pre_process(text):
    text = text.strip()
    text = text.lower()
    return text

review_text = "   Headphones are in good condition   "
result = (lambda word: pre_process(word))
print(result(review_text))
headphones are in good condition

Here we have used a user defined function inside lambda function.


Default image
Asha Ponraj

Data science and Machine Learning enthusiast | Software Developer | Blog Writter

Articles: 84

Leave a Reply