A name is a convention that is used to refer to or address any entity. Almost everything around us has a name. The world of programming also goes in accordance to this. But is it a must to name everything? Or can you have something that is just ‘anonymous’? The answer is, yes. Python provides Lambda Functions, also known as Anonymous functions that are in fact nameless. So let’s move ahead to learn about these ‘Anonymous Mysteries’ of Python, in the following sequence.
- Why are Python Lambda Functions required?
- What are Python Lambda Functions?
- How to write Lambda Functions?
- How do Anonymous functions reduce the size of the code?
- Python Lambda functions within user defined functions
- How to use Anonymous functions within:
So let’s begin 🙂
Why use Python Lambda Functions?
The main purpose of anonymous functions come into picture when you need some function just once. They can be created wherever they are needed. Due to this reason, Python Lambda Functions are also known as throw-away functions which are used along with other predefined functions such as filter(), map(), etc. These functions help reduce the number of lines of your code when compared to normal python functions.
To prove this, let’s move on further and learn about Python Lambda functions.
What are Python Lambda Functions?
Python Lambda functions are functions that do not have any name. They are also known as anonymous or nameless functions. The word ‘lambda’ is not a name, but its a keyword. This keyword specifies that the function that follows is anonymous.
Now that you are aware of what these anonymous functions refer to, let us move further to see how you write these Python Lambda functions.
How to write Lambda Functions in Python?
A Lambda function is created using the lambda operator and its syntax is as follows:
lambda arguments: expression
Python lambda function can have any number of arguments but it takes just one expression. The inputs or arguments can start at 0 and go up to any limit. Just like any other functions, it’s perfectly fine to have lambda functions with no inputs. Therefore, you can have lambda functions in any of the following formats:
lambda : “Specify the purpose”
Here, the lambda function is not taking any arguments.
lambda a1: “Specify the use of a1“
Here, lambda is taking one input which is a1.
Similarly, you can have lambda a1, a2, a3..an.
Let’s take a few examples to demonstrate this:
a = lambda x: x*x print(a(3)
a = lambda x,y: x*y print(a(3,7))
As you can see, I have taken two examples here. The first example makes use of the lambda function with just one expression whereas the second example has two arguments passed to it. Please note that both functions have a single expression followed by the arguments. Therefore, lambda functions cannot be used where you need multi-line expressions.
On the other hand, normal python functions can take any number of statements in their function definitions.
How do Anonymous functions reduce the size of the code?
Before comparing the amount of code required, let’s first write down the syntax of normal functions and compare it with that of lambda functions described earlier.
Any normal function in Python is defined using a def keyword as follows:
As you can see, the amount of code required for a lambda function is quite less than that of normal functions.
Let us rewrite the example we took earlier using normal functions now.
def my_func(x): return x*x print(my_func(3))
As you can see, in the above example, we need a return statement within the my_func to evaluate the value of the square of 3. Contrarily, the lambda function does not make use of this return statement, but, the body of the anonymous function is written in the same line as the function itself, after the colon symbol. Therefore the size of the function is smaller than that of my_func.
However, lambda functions in the above examples, are called using some other variable a. This is done because these functions are nameless and therefore require some name to be called. But, this fact might seem confusing as to why use such nameless functions when you need to actually assign some other name to call them? And of course, after assigning the name a to my function, it doesn’t remain nameless anymore! Right?
It’s a legitimate question, but the point is, this is not the right way of using these anonymous functions.
Anonymous functions are best used within other higher-order functions that either make use of some function as an argument or, return a function as the output. To demonstrate this, let us now move on towards our next topic.
Python Lambda functions within user-defined functions:
Like mentioned above, lambda functions are used within other functions to mark the finest advantage.
The following example consists of new_func which is a normal python function that takes one argument x. This argument is then added to some unknown argument y which is supplied through the lambda function.
def new_func(x): return(lambda y: x+y) t=new_func(3) u=new_func(2) print(t(3)) print(u(3))
As you can see, in the above example, the lambda function which is present within new_func is called whenever we make use of new_func(). Each time, we can pass separate values to the arguments.
Now that you have seen how to use anonymous functions within higher-order functions, let us now move ahead to understand one of its most popular use that is within the filter(), map() and reduce() methods.
How to use Anonymous functions within filter(), map() and reduce():
Anonymous functions within filter():
The filter() method is used to filter the given iterables(lists, sets, etc) with the help of another function, passed as an argument, to test all the elements to be true or false.
The syntax of this function is :
Now consider the following example:
my_list = [2,3,4,5,6,7,8] new_list = list(filter(lambda a: (a/3 == 2), my_list)) print(new_list)
Here, my_list is a list of iterable values which is passed to the filter function. This function uses the lambda function to check if there are any values in the list, that will equate to 2 when divided by 3. The output consists of a list that satisfies the expression present within the anonymous function.
The map() function in Python is a function that applies a given function to all the iterables and returns a new list.
Let’s take an example to demonstrate the use of the lambda functions within the map() function:
my_list = [2,3,4,5,6,7,8] new_list = list(map(lambda a: (a/3 != 2), li)) print(new_list)
The above output shows that, whenever the value of the iterables is not equal to 2 when divided by 3, the result returned should be True. Hence, for all elements in my_list, it returns true except for the value 6 when the condition changes to False.
The reduce() function is used to apply some other function to a list of elements that are passed as a parameter to it and finally returns a single value.
The syntax of this function is as follows:
from functools import reduce reduce(lambda a,b: a+b, [23,21,45,98])
The above example is depicted in the following image:
The output clearly shows that all the elements of the list are added continually to return the final result.
With this, we come to the end this article on ‘Python Lambda’. Hope you are clear with all that has been shared with you. Make sure you practice as much as possible and revert your experience.
Got a question for us? Please mention it in the comments section of this “Python Lambda” blog and we will get back to you as soon as possible.
To get in-depth knowledge on Python along with its various applications, you can enroll for live Python online training with 24/7 support and lifetime access.