Python Lambda Function Tutorial – Working with Lambda Functions

In this post, we will learn about Python Lambda Function. It is also called the anonymous function.

What is Python Lambda Function?

We create function all the time in any programming language. In python, we do it by using the def keyword. What we do is we write def function-name( parameters ):. Notice we have the name of the function after the def keyword for example def get_square( x ):. But lambda functions are the functions with no name, and it is also called anonymous functions. To define a lambda function we use the keyword lambda.

Making a Python Lambda function

Syntax

To define a lambda function in python we have the following syntax.

When using lambda you need to understand that you can use any number of arguments but only a single expression. So you can only use lambdas when you have one and only one expression in your function.

Example of Lambda Function

Now let’s see a real example of python lambda function. I will make it really simple, so assume we want a function that should calculate square of a given number.

As you can see we have a very simple lambda function that will calculate the square of a given number.

python lambda function
Python Lambda Function

As you can see in the above code, we have a function with no name. The function is taking a single argument x. And the expression is x * x. So it will return the square of x. The lambda is assigned to the identifier square. And we can use the square identifier to call the lambda function.

When to Use Lambda Function?

lambda keyword is a shortcut for defining small functions. So when you want a quick fix for some small things lambda functions are better option. You do not even need to specify a name or assign it with an identifier.

For example if we consider the same code that we written above then, instead of assigning lambda to a square we can do it this way as well.

Using Lambda with Filter

In python we have a function filter. It takes two arguments the first one is a function where we can pass lambda function, the next argument is the list. Filter creates a new list if the function evaluates true for each item in the list. So it becomes very handy while performing operations like filter.

Assuming we need to find out all the numbers divisible with 3 in a list then we can consider the following code.

Conclusion

Python Lambda Functions are nothing but only a fancy way of defining a single expression functions. It is sometime useful when you want to do some quick things.

So that is all for this post friends, if you are having any confusion regarding python lambda function then let me know in comments. Thank You 🙂

1 thought on “Python Lambda Function Tutorial – Working with Lambda Functions”

Leave a Comment