In this article, you’ll learn about the anonymous functions, which are also known as the Lambda functions. You’ll learn what they’re, their syntax, and the way to use them (with examples). This is a Complete Guide of Python Lambda Functions which will help you so The topics which we will be discussing in this article are as follows:
This article was published as a part of the Data Science Blogathon
In Python, an lambda/anonymous function may be a function that’s defined without a reputation.
While defining normal functions, we are using the def keyword in Python, but while defining anonymous functions we are using the lambda keyword.
Hence, anonymous functions also are called Lambda functions.
A lambda function in python has the subsequent syntax.
Syntax of Lambda Function in Python:
lambda arguments: expression
Note that the Lambda functions can have any number of arguments but they have only one expression. Firtsly, the expression is evaluated and then returned. We used Lambda functions wherever function objects are required.
In this section, we will see the example of a lambda function that doubles (i.e, multiply by two) the input value.
Program to indicate the utilization of Lambda functions:
double = lambda x: x * 2
print(double(10))
Code Explanation:
In the above code, lambda x: x * 2 is the lambda function. Also, their x is the argument and x * 2 is the expression that gets evaluated and returned to the user.
This function has no name. It returns a function object which is assigned to the identifier double. we will now call it a standard function. The statement
double = lambda x: x * 2
is nearly identical as:
def double(x): return x * 2
We use lambda functions once we require a nameless function for a brief period of your time.
In Python, we generally use Lambda Functions as an argument to a higher-order function (a function that takes in other functions as arguments).
For Example, These are used together with built-in functions like filter(), map(), and reduce(), etc, which we will discuss later in this article.
As you may see in the previous section, lambdas are treated identically to regular functions at the interpreter level. In a way, you’ll say that lambdas provide compact syntax for writing functions that return one expression.
However, you must know when it’s a decent idea to use lambdas and when to avoid them. During this section, you may learn a number of the look principles utilized by python developers when writing lambdas.
One of the foremost common use cases for lambdas is in functional programming as Python supports a paradigm (or style) of programming referred to as functional programming.
It allows you to supply a function as a parameter to a different function (for example, in map, filter, etc.). In such cases, using lambdas offer a sublime thanks to creating a one-time function and pass it as the parameter.
In a production environment, You should never write complicated lambda functions, as it’ll be very difficult for coders who maintain your code to decrypt it. If you discover yourself making complex one-liner expressions, it might be a way superior practice to define a correct function.
Therefore, as a best practice, you wish to recollect that easy code is often better than complex code.
The filter function is employed to pick some particular elements from a sequence of elements. The sequence used in this function is an iterator such as lists, sets, tuples, etc.
The elements which can be selected are predicated on some pre-defined constraint. It takes 2 parameters:
sequences = [10,2,8,7,5,4,3,11,0, 1]
filtered_answer = filter (lambda x: x > 6, sequences)
print(list(filtered_answer))
Output:
[10, 8, 7, 11]
Code Explanation:
The map function is employed to use a specific operation for each element in a sequence. Like filter(), it also takes 2 parameters:
In this example, we could make a program that prints the squares of numbers in an exceedingly given list:
sequences = [10,2,8,7,5,4,11]
squared_result = map (lambda x: x*x, sequences)
print(list(squared_result))
Output:
[100, 4, 64, 49, 25, 16, 121]
Code Explanation:
The reduce function, like map(), is employed to use an operation to each element in a sequence. However, it’s working is a bit differs from the map function. The following steps are to be followed by the reduce() function to compute an output:
Step-1: Perform the defined operation on the primary 2 elements of the sequence.
Step-2: Save this result
Step-3: Perform the operation with the saved result and therefore the next element within the sequence.
Step-4: Repeat until no more elements are left.
It also takes two parameters:
In this example, we will make a program that returns the product of all elements present in a list given by the user.
from functools import reduce
sequences = [1,2,3,4,5,6]
product = reduce (lambda x, y: x*y, sequences)
print(product)
Output:
720
Code Explanation:
This ends our discussion!
The syntax for a lambda function is generally the following:
lambda arguments: expression
Here’s a breakdown of the syntax:
lambda
: This keyword signifies that you’re defining a lambda function.arguments
: This is a comma-separated list of arguments that the function can take. These arguments act like placeholders for the values that will be passed into the function when it’s called.colon (:)
: This separates the arguments from the expression.expression
: This is the code that the function will execute. Unlike regular functions, lambda functions can only have one expression. This expression is evaluated and returned as the function’s output.Here are some key points to remember about lambda functions:
For instance, in Python, you can use a lambda function to double a number:
double = lambda x: x * 2
# Call the lambda function
result = double(5)
print(result) # Output: 10
Both def
and lambda
are used to define functions in Python, but there are some key differences between them:
Definition:
def
: Used to define regular named functions. These functions can be multi-line and can contain complex logic including loops, conditional statements, and other function calls.lambda
: Used to define anonymous functions, also known as lambda functions. These functions are typically single-line expressions and are limited in their complexity.Use Cases:
def
: Suitable for defining functions that you plan to reuse throughout your code or functions that require complex logic.lambda
: Suitable for short, simple functions that are used only once or in a specific context, such as with built-in functions like map
, filter
, or reduce
.Lambda functions in Python offer concise, anonymous function declarations ideal for one-liners and functional programming paradigms. They’re handy for quick operations, especially in filter(), map(), and reduce(). However, they might not suit complex logic or readability needs, where traditional def-defined functions are preferable for clarity and reusability. So at the End of this Article You have a complete understanding of python lambda Functions.
I hope you enjoyed the article.
If you want to connect with me, please feel free to contact me on Email
Your suggestions and doubts are welcomed here in the comment section. Thank you for reading my article!
The media shown in this article are not owned by Analytics Vidhya and are used at the Author’s discretion.