Python Lambda Functions
If you want to work with a temporary function to filter data or apply transformations, without using the def keyword, then you can create a quick, and small Lambda function. Lambda functions are very powerful tools in Python that can be created without a name. If you understand the use of Lambda Functions in Python, then you can create clean and concise codes.
Table of Contents
A Lambda function is created by using the lambda keyword. It is a small function with no name and can take multiple arguments. These functions are restricted to single expressions and can be used only once.
Example:
#creating lambda function
cube = lambda x: x * x * x
print(cube(4))
Properties of Python Lambda Functions
Here are some of the properties of Python lambda functions:
- Anonymous: Lambda functions are anonymous, meaning they do not have a name. This makes them ideal for short, one-off tasks.
- Inline: Lambda functions can be defined inline, meaning they can be defined within the same line of code as the function call. This makes them even more concise and easier to read.
- Single expression: Lambda functions can only contain a single expression. This expression is evaluated and the result is returned.
- Can take arguments: Lambda functions can take arguments, just like regular functions. However, lambda functions can only have a single expression, so the arguments must be used in that expression.
- Can be assigned to variables: Lambda functions can be assigned to variables, just like regular functions. This allows you to store the lambda function for later use.
Can be used with other functions: Lambda functions can be used with other functions, such as the map() and filter() functions. This allows you to perform complex tasks with ease.
Key Features of Python Lambda Functions
There are some key features of lambda functions in Python that make them a powerful tool that simplifies data processing abilities and helps developers process data efficiently. Following are some of the key features:
- A Lambda function is anonymous in nature as it doesn’t require any name, and can only be used once.
- A lambda function can only contain a single expression as it keeps them concise and helps in writing clear codes.
- A lambda function can take multiple arguments which makes it flexible for operations.
- A lambda function returns values automatically after evaluating the expression. There’s no need for a return statement.
- Lambda functions are lightweight as they are just one-line statements and do not require full function definition.
Master Python Programming
From Beginner to Pro in Just Weeks – Start Your Coding Journey Today!
Benefits of Lambda Function in Python
If you want to simplify your code and improve efficiency, the Python lambda function offers a wide range of benefits. Following are some of the advantages of lambda function:
- One of the benefits of lambda functions is that it is written in a single line which makes the code clearer and concise.
- There is no need to define a name or write multiple lines of code to create a lambda function which makes it easy to implement.
- Lambda functions are defined as per use and are for single use only, this improves code readability.
- Lambda functions are flexible because they allow developers to create anonymous functions for specific needs.
Syntax of Python Lambda Function
As you’ve learned this far, Python Lambda functions are easy to write and have a very concise syntax. All the other functions in Python are created using the def keyword but the lambda functions are just one-line statements that do not require a name.
lambda = arguments: expression
Where,
- lambda is the keyword used to define a function
- arguments that take input values for the function. There can be 0 or more arguments.
- expression that are single-line codes that are executed and return results.
Example:
#creating a lambda function
cube = lambda x: x * x * x
print(cube(4))
Here,
- x is the argument
- x * x * x is the expression that calculates the cube
How to Create a Lambda Function in Python?
It is very easy to create a Lambda function in Python because of its very basic syntax. Following are the steps that you can follow to create a lambda function:
- Step 1: Start by using the lambda keyword to indicate that you are creating a function.
- Step 2: Specify the arguments that you require in the function. Separate these arguments using commas.
- Step 3: Write the expression that will execute and return the result.
Example 1: With one argument
#creating lambda function
square = lambda x: x * x
print(square(4)) #Output: 16
Example 2: With multiple arguments
#creating lambda function
sum = lambda x, y: x + y
print(sum(4,5)) #Output: 9
Example 3: Without arguments
#creating lambda function
const = lambda: 30
print(const()) #Output: 30
Example 4: Inline Lambda Function
#creating inline lambda function
print((lambda x: x * x)(4)) #Output: 16
Learn Python, Step by Step
Unlock the Power of Coding – Build Skills for the Future!
Difference between Lambda and def function in Python
Lambda and def both are keywords that are used to define functions in Python. However, their structure and use cases are different from each other. Following are some of the differences between both:
Lambda vs def Function in Python
Feature |
Lambda |
def |
Definition |
A lambda function is a one-line statement that can be used only once |
A def function can include multiple statements and is reusable. |
Syntax |
lambda arguments: expression |
def function_name(arguments) :
statements |
Readability |
For complex expressions, lambda functions are difficult to read |
def functions are more readable with complex expressions as they can be divided into multiple lines |
Reusability |
lambda functions are scope-restricted and can be used only once |
def functions can be used multiple times as they are not scope-restricted |
Debugging |
It is difficult to debug a lambda function because it is a nameless function and complex expressions can complicate a lambda function |
Debugging a def statement is easier as it is easy to read, more descriptive, and can also include print statements. |
Using Lambda function with map()
If you have a list of data and you want to apply a specific operation to all of the values in that list, you can use the map() function. When you use the map() along with the lambda function, it becomes an easier and more efficient way to process data.
Syntax:
map(function, iterable)
Here, the function is the lambda expression that is to be applied on each iterable(list or tuple).
Example:
#creating a list
num = [1, 2, 3, 4, 5]
#Applying map() function
cube = list(map(lambda x: x**3, num))
print(cube) #Output: [1, 8, 27, 64, 125]
Using Lambda function with filter()
If you want to filter your data using a specific condition and extract that data out of a list of elements. You can combine this filter() function with the lambda function for quick and easy operations.
Syntax:
filter(function, iterable)
Here, the function is the lambda expression that is applied to the iterable(list or tuple), and elements which return True will be returned as a result.
Example:
#create a list
num = [1, 2, 3, 4, 5, 6]
#Applying filter() function
odd_numbers = list(filter(lambda x: x % 2 != 0, num))
print(odd_numbers) #Output: [1, 3, 5]
Using Lambda function with reduce()
If you want to perform a cumulative operation on a sequence, then you can use the reduce() function from the functools module. With the use of reduce() function, you can perform an operation and the final result will be a single value.
Syntax:
reduce(function, iterable)
Here, the function is the lambda expression and is iterable(list or tuple). Once an operation is performed on an element, then it becomes the first argument for the next iterable.
Example:
#Importing reduce from functools
from functools import reduce
#create a list
num = [1, 4, 6, 24, 57, 62, -2]
#applying the reduce() function
minimum = reduce(lambda x, y: y if x > y else x, num)
print(minimum) # Output: -2
Comparison between map(), filter() and reduce() function
Function |
Operation |
Example |
map() |
To apply an expression and perform operation on all items of the iterable |
Cube of all numbers in a list |
filter() |
To filter out an item from the list based on a condition |
Filter out odd numbers from a list |
reduce() |
To perform a cumulative operation on a sequence |
Find the minimum or maximum number from the list |
Get 100% Hike!
Master Most in Demand Skills Now!
Conclusion
In this article, you have learned about the importance and use case of lambda function. Here’s a recap for you, Lambda function is a quick and easy-to-write expression that can perform operations on a list of elements. The scope of a lambda function is specific to the block where it is created, but it can integrate with other tools like map(), filter(), and reduce() to perform operations on a list of elements. Unlike regular functions, lambda functions save time and make the code easy to read.
FAQs
Define Lambda Function.
A lambda function in Python is used to perform operations on a single expression. It can accept any number of arguments but its scope is restricted.
Give Syntax of a Lambda Function.
Following is the syntax of the lambda function:
lambda arguments: expression
What is the difference between lambda function and regular function?
A lambda function is anonymous and scope-restricted, it can only work on a single expression whereas a regular function has a name, can work on multiple statements, and is reusable.
Can lambda functions be assigned to variables?
Yes, lambda functions can be assigned to variables. Lambda functions can be used with or without variables.
Example: With variable: num = lambda x: x * x, Without variable: print((lambda x: x * x)(4))
Can a lambda function be used for multiple expressions?
No, a lambda function is scope-restricted and hence can only be used for a single expression.
Our Python Courses Duration and Fees
Cohort starts on 14th Jan 2025
₹20,007