
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Use Lambda Function in Python
Lambda Function in Python
Lamda functions are inline functions, i.e., functions that are written in a single line instead of using multiple lines. These are anonymous functions (functions without a name).
We can define a lambda function using the lambda keyword. These are typically used when we need to return a function from another function or accept a function as a parameter.
We can also use lambda functions with built-in functions like map(), filter(), and sorted(), where we need to perform a small operation quickly without writing a separate full function.
Lamda function is basically a shortcut for writing a function with a return statement in one line. we use these where we don't need to define a function using the def keyword.
Syntax of a Lambda Function
Following is the basic syntax of a lambda function -
lambda arguments: expression
Here,
- arguments is the input (can be one or more).
- expression is the single line of logic to run and return.
Example: Lambda Function to Add Two Numbers
Let us look at an example where we add two numbers using both a regular function and a lambda function -
# Regular function def add(x, y): return x + y # Same functionality using lambda add_lambda = lambda x, y: x + y print("Regular Function",add(5, 3)) print("Using Lambda",add_lambda(5, 3))
As you can see, both the regular function and the lambda function return the same result. The lambda function provides a shorter way to achieve the same functionality -
Regular Function 8 Using Lambda 8
Using Lambda with map() Function
The map() function in Python is used to apply a function to each element of an iterable (like a list or tuple) and returns a new iterable with the results. When combined with a lambda function, it becomes a quick way to transform data without defining a separate function using def.
Syntax
Following is the basic syntax of using lambda with the map() function -
map(function, iterable)
Here,
- function: It is a function to apply to each item. This can be a lambda function.
- iterable: It is the collection of items you want to process (like a list).
Example: Square Each Number in a List
Let us use a lambda function with map() function to square each number in a list -
numbers = [1, 2, 3, 4] # Using lambda with map to square each number squared = list(map(lambda x: x ** 2, numbers)) print("Original:", numbers) print("Squared:", squared)
Following is the output obtained -
Original: [1, 2, 3, 4] Squared: [1, 4, 9, 16]
Using Lambda with filter() Function
The filter() function in Python is used to filter items from an iterable based on a condition. It returns a new iterable containing only the items for which the provided function returns True.
When combined with a lambda function, it becomes an easy way to write short filtering logic without creating a full function using def.
Syntax
Following is the basic syntax of using lambda with filter() function -
filter(function, iterable)
Here,
- function: is a function that returns True or False for each item.
- iterable: is the collection of items you want to filter.
Example: Filter Even Numbers
In this example, we use a lambda function with filter() function to filter even numbers from a list -
numbers = [1, 2, 3, 4, 5, 6] # Filter even numbers using lambda even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) print("Even Numbers:", even_numbers)
We get the output as shown below -
Even Numbers: [2, 4, 6]
Using Lambda with sorted() Function
The sorted() function in Python is used to return a new sorted list from the elements of any iterable. By default, it sorts in ascending order, but you can customize the sorting using a key parameter.
When combined with a lambda function, it allows us to define custom sorting logic in a single line without creating a separate function using def.
Syntax
Following is the basic syntax of using lambda with sorted() function -
sorted(iterable, key=lambda item: expression)
Here,
- iterable: is the collection of items to sort.
- key: is a function (often a lambda) that returns the value to sort by.
Example: Sort List of Tuples by Second Element
In the following example, we use a lambda function to sort a list of tuples based on the second element of each tuple -
data = [(1, 3), (4, 1), (2, 2)] # Sort by second element sorted_data = sorted(data, key=lambda x: x[1]) print("Sorted by Second Element:", sorted_data)
Following is the output of the above code -
Sorted by Second Element: [(4, 1), (2, 2), (1, 3)]
Assigning Lambda Function to a Variable
You can assign a lambda function to a variable, which allows you to use it just like a regular function defined with def. This is useful when you want to reuse the lambda multiple times in your program or give it a more meaningful name.
Once assigned to a variable, the lambda function behaves exactly like any other function. You can call it with arguments, pass it to other functions, or even use it inside data structures.
Example: Lambda to Multiply Two Numbers
In this example, we assign a lambda function to a variable called multiply. This lambda takes two arguments and returns their product -
# Assigning lambda to a variable multiply = lambda a, b: a * b # Using the lambda function print(multiply(4, 5))
We get the output as shown below -
20
When to Use Lambda Functions
Lambda functions are best used when -
- You need a small function for a short task.
- You do not want to reuse the function elsewhere.
- You want to pass a function as an argument to another function.
Limitations of Lambda Functions
Although lambda functions are useful, they also have some limitations -
- They can only contain one expression.
- No multiple statements or complex logic.
- They are less readable if overused.