In Python programming, lambda functions, also commonly referred to as anonymous functions, are a unique and concise way of creating small, unnamed functions. Unlike traditional functions declared with the def keyword, lambda functions are defined using the lambda keyword. Lambda functions are particularly useful in scenarios where a quick, disposable function is needed for a short period.
- lambda Keyword: This keyword signifies the start of an anonymous function.
- Parameters: These are similar to parameters in a regular function. A lambda function can have any number of parameters, including zero. These parameters are listed before the colon.
- Expression: After the colon, you write a single expression that the function will evaluate and return. Unlike regular functions, a lambda function is limited to a single expression and cannot contain multiple statements or commands.
It is possible to use the lambda function only once and execute it simultaneously when it is defined, and due to this property, it is also called an anonymous function.
This anonymous function is beneficial when we want to pass functions as an argument to the other functions.
The above example has a single argument, x, and we have written the entire lambda function inside a print statement.
Here, we passed 4 as a parameter as soon as we defined the lambda function.
The above code will print the value 10, which is nothing but the addition of 6 and 4.
In the lambda function, we can pass multiple arguments but only a single expression, so obviously, it can’t be replaced with the regular function, which has loops and conditionals in its definition.
Why Use Lambda Functions?
Lambda functions in Python are not just a stylistic choice; they offer several practical benefits that make them a valuable tool for developers:
Simplicity and Conciseness: Lambda functions provide a straightforward way to define small functions in a single line. This conciseness is particularly useful for small operations that are too minor to justify writing a full function with the def keyword.
No Need for Function Names: In scenarios where a function is required temporarily and for a short task, using a lambda function eliminates the need to formally name the function. This is useful in coding situations where the function's purpose is clear and self-contained within its use.
Functional Programming Style: Lambda functions fit well with the functional programming style in Python. They work seamlessly with functions like map(), filter(), and reduce(), which expect function objects as arguments. For instance, they can be used to apply an operation to each item in a list or to filter a list based on a condition.
Common Use Cases for Lambda Function in Python
Lambda functions are versatile and can be used in various scenarios in Python programming. Here are some common use cases:
1. Lambda Function with Iterables
As the name suggests, the filter() function in Python will help us to filter the lists.
The filter() function takes two arguments: the first is the lambda function as an anonymous function, and the second argument is the list of numbers.
When we call the filter function, it iterates over the provided list and passes every value one by one to the function, which returns true or false.
If that particular value's result is true, it gets added to the list. The classic example of lambda functions with the filter() method is to filter out the even or odd numbers from a list of numbers.
The Python map() function is mostly used to modify the items in the list.
It takes two arguments: the first argument is the lambda function as an anonymous function, and the second argument is the list.
The map() function iterates over the list provided as a parameter, and each value is passed as a parameter to evaluate with the expression of the lambda function. Then, these evaluated values are returned one after another.
Suppose we want to create a list of squares of numbers from the given list of numbers.
The Python reduce() function is mostly used to reduce the entire list into a single result.
The reduce() function needs to be imported from the functools module. Functools is one of the modules in Python which contains some higher-order functions.
The reduce() function takes two arguments: the first is the function, and the second is the list.
The reduce() function iterates over the given list of numbers, and these numbers are passed to the lambda function as a parameter. When the entire list is iterated, the final result is returned by the reduce() function.
Let’s suppose we have the list of numbers and add up all these numbers.
2. Lambda Function with List Comprehension
Lambda functions can be effectively combined with list comprehensions to perform operations on list elements. For example, you can use a lambda function within a list comprehension to square each number in a list:
3. Lambda Function with if-else
You can incorporate conditional logic within a lambda function. This is useful for simple conditional operations. For instance, a lambda function can return different values based on a condition:
4. Lambda Function with Multiple Statements
While lambda functions are limited to a single expression, you can mimic multiple statements by using techniques like logical operators or tuple unpacking. However, this can sometimes reduce readability. For example:
Note: This approach is generally discouraged as it goes against the lambda function's purpose of simplicity and clarity.
5. Lambda Function with Pandas Series
In data analysis with Pandas, lambda functions are frequently used to apply operations to Series or DataFrame columns. For instance, you can use a lambda function to transform data in a Pandas Series:
Each of these use cases demonstrates how lambda functions can be employed to write more concise and readable code in Python, particularly for small-scale operations or data manipulation tasks.
- The lambda function in Python can be used at various places, and its powers are being utilized to write clean and simple code.
- This Python lambda function gives a very elegant way to do complex things easily.
- The power of the lambda functions is utilized when they are used with some other functions like filter(), map(), reduce(), etc.