In this article, we will discuss briefly about Python Lambda function along with an example.
A Lambda function is an anonymous function which takes arguments and returns an evaluated expression. Let us see how the syntax of Python Lambda function looks like.
Table of Contents
Lambda Function Syntax
Before seeing examples, the following are the characteristics of a Python Lambda function which are noteworthy:
- A Lambda function can have any number of arguments but only one expression, which will be evaluated and returned.
- We are free to use lambda functions wherever function objects are required.
- return keyword is not used in Lambda function as by default lambas return a value.
Now let us create a Lambda function using Python.
Below is the lambda function to print a square of a given number:
Let us see a Lambda function accepting multiple arguments.
The output is 24.
Usage of Lambdas in Built-in Functions
There are some built-in functions like map(), filter(), reduce() etc. which takes a lambda as an argument.
Let us see how filter function works.
A filter() takes two parameters as arguments – a lambda function and a list. It filters the passed list and returns the values which matches the condition set by a lambda function.
Let us see an example where we want to find out the below average marks in a list.