Python Lambda Functions are anonymous functions means that the function is without a name. As we already know the def keyword is used to define a normal function in Python. Similarly, the lambda keyword is used to define an anonymous function in Python.
Python Lambda Function Syntax
Syntax: lambda arguments : expression
- This function can have any number of arguments but only one expression, which is evaluated and returned.
- One is free to use lambda functions wherever function objects are required.
- You need to keep in your knowledge that lambda functions are syntactically restricted to a single expression.
- It has various uses in particular fields of programming, besides other types of expressions in functions.
Python Lambda Function Example
In the example, we defined a lambda function(upper) to convert a string to its upper case using upper().
This code defines a lambda function named upper
that takes a string as its argument and converts it to uppercase using the upper()
method. It then applies this lambda function to the string ‘GeeksforGeeks’ and prints the result
Python
str1 = 'GeeksforGeeks'
upper = lambda string: string.upper()
print(upper(str1))
Output:
GEEKSFORGEEKS
Use of Lambda Function in Python
Let’s see some of the practical uses of the Python lambda function.
Condition Checking Using Python lambda function
Here, the ‘format_numric’ calls the lambda function, and the num is passed as a parameter to perform operations.
Python
format_numeric = lambda num: f"{num:e}" if isinstance(num, int) else f"{num:,.2f}"
print("Int formatting:", format_numeric(1000000))
print("float formatting:", format_numeric(999999.789541235))
Output:
Int formatting: 1.000000e+06
float formatting: 999,999.79
Difference Between Lambda functions and def defined function
The code defines a cube function using both the ‘def'
keyword and a lambda function. It calculates the cube of a given number (5 in this case) using both approaches and prints the results. The output is 125 for both the ‘def'
and lambda functions, demonstrating that they achieve the same cube calculation.
Python
def cube(y):
return y*y*y
lambda_cube = lambda y: y*y*y
print("Using function defined with `def` keyword, cube:", cube(5))
print("Using lambda function, cube:", lambda_cube(5))
Output:
Using function defined with `def` keyword, cube: 125
Using lambda function, cube: 125
As we can see in the above example, both the cube() function and lambda_cube() function behave the same and as intended. Let’s analyze the above example a bit more:
With lambda function
| Without lambda function
|
---|
Supports single-line sometimes statements that return some value. | Supports any number of lines inside a function block |
Good for performing short operations/data manipulations. | Good for any cases that require multiple lines of code. |
Using the lambda function can sometime reduce the readability of code. | We can use comments and function descriptions for easy readability. |
Practical Uses of Python lambda function
Python Lambda Function with List Comprehension
On each iteration inside the list comprehension, we are creating a new lambda function with a default argument of x (where x is the current item in the iteration). Later, inside the for loop, we are calling the same function object having the default argument using item() and get the desired value. Thus, is_even_list stores the list of lambda function objects.
Python
is_even_list = [lambda arg=x: arg * 10 for x in range(1, 5)]
for item in is_even_list:
print(item())
Output:
10
20
30
40
Python Lambda Function with if-else
Here we are using the Max lambda function to find the maximum of two integers.
Python
Max = lambda a, b : a if(a > b) else b
print(Max(1, 2))
Output:
2
Python Lambda with Multiple Statements
Lambda functions do not allow multiple statements, however, we can create two lambda functions and then call the other lambda function as a parameter to the first function. Let’s try to find the second maximum element using lambda.
The code defines a list of sublists called ‘List'
. It uses lambda functions to sort each sublist and find the second-largest element in each sublist. The result is a list of second-largest elements, which is then printed. The output displays the second-largest element from each sublist in the original list.
Python
List = [[2,3,4],[1, 4, 16, 64],[3, 6, 9, 12]]
sortList = lambda x: (sorted(i) for i in x)
secondLargest = lambda x, f : [y[len(y)-2] for y in f(x)]
res = secondLargest(List, sortList)
print(res)
Output:
[3, 16, 9]
Lambda functions can be used along with built-in functions like filter(), map() and reduce().
Using lambda() Function with filter()
The filter() function in Python takes in a function and a list as arguments. This offers an elegant way to filter out all the elements of a sequence “sequence”, for which the function returns True. Here is a small program that returns the odd numbers from an input list:
Filter out all odd numbers using filter() and lambda function
Here, lambda x: (x % 2 != 0) returns True or False if x is not even. Since filter() only keeps elements where it produces True, thus it removes all odd numbers that generated False.
Python
li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61]
final_list = list(filter(lambda x: (x % 2 != 0), li))
print(final_list)
Output:
[5, 7, 97, 77, 23, 73, 61]
Filter all people having age more than 18, using lambda and filter() function
The code filters a list of ages and extracts the ages of adults (ages greater than 18) using a lambda function and the ‘filter'
function. It then prints the list of adult ages. The output displays the ages of individuals who are 18 years or older.
Python
ages = [13, 90, 17, 59, 21, 60, 5]
adults = list(filter(lambda age: age > 18, ages))
print(adults)
Output:
[90, 59, 21, 60]
Using lambda() Function with map()
The map() function in Python takes in a function and a list as an argument. The function is called with a lambda function and a list and a new list is returned which contains all the lambda-modified items returned by that function for each item. Example:
Multiply all elements of a list by 2 using lambda and map() function
The code doubles each element in a list using a lambda function and the ‘map'
function. It then prints the new list with the doubled elements. The output displays each element from the original list, multiplied by 2.
Python
li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61]
final_list = list(map(lambda x: x*2, li))
print(final_list)
Output:
[10, 14, 44, 194, 108, 124, 154, 46, 146, 122]
Transform all elements of a list to upper case using lambda and map() function
The code converts a list of animal names to uppercase using a lambda function and the ‘map'
function. It then prints the list with the animal names in uppercase. The output displays the animal names in all uppercase letters.
Python
animals = ['dog', 'cat', 'parrot', 'rabbit']
uppered_animals = list(map(lambda animal: animal.upper(), animals))
print(uppered_animals)
Output:
['DOG', 'CAT', 'PARROT', 'RABBIT']
Using lambda() Function with reduce()
The reduce() function in Python takes in a function and a list as an argument. The function is called with a lambda function and an iterable and a new reduced result is returned. This performs a repetitive operation over the pairs of the iterable. The reduce() function belongs to the functools module.
A sum of all elements in a list using lambda and reduce() function
The code calculates the sum of elements in a list using the ‘reduce'
function from the ‘functools'
module. It imports ‘reduce'
, defines a list, applies a lambda function that adds two elements at a time, and prints the sum of all elements in the list. The output displays the computed sum.
Python
from functools import reduce
li = [5, 8, 10, 20, 50, 100]
sum = reduce((lambda x, y: x + y), li)
print(sum)
Output:
193
Here the results of the previous two elements are added to the next element and this goes on till the end of the list like (((((5+8)+10)+20)+50)+100).
Find the maximum element in a list using lambda and reduce() function
The code uses the ‘functools'
module to find the maximum element in a list (‘lis'
) by employing the ‘reduce'
function and a lambda function. It then prints the maximum element, which is 6 in this case.
Python
import functools
lis = [1, 3, 5, 6, 2, ]
print("The maximum element of the list is : ", end="")
print(functools.reduce(lambda a, b: a if a > b else b, lis))
Output:
The maximum element of the list is : 6
Python Lambda Functions – FAQs
What is the benefit of lambda function Python?
Lambda functions provide a concise way to create small anonymous functions without needing to define a formal function using def. They are particularly useful in situations where a small function is needed temporarily or where the function definition is straightforward and can be expressed in a single line.
What is the difference between def and lambda in Python?
The main differences between def and lambda functions are:
- Syntax: Lambda functions are written with the lambda keyword followed by parameters and an expression, while def functions have a full function header, body, and can contain multiple statements.
- Return: Lambda functions implicitly return the result of evaluating the expression, while def functions use an explicit return statement.
- Scope: Lambda functions are limited to a single expression, making them more restrictive than def functions, which can contain multiple statements and have more complex logic.
What is the functionality of lambda?
The functionality of lambda functions in Python is to create small, anonymous functions on the fly. They are often used in situations where creating a full-fledged function using def would be overkill or where a function is needed for a short period and doesn’t need a name.
When to use lambda?
Lambda functions are suitable for:
- Simple operations: When you need to perform simple operations or calculations.
- Anonymous functions: When you need a function temporarily or in one place and don’t want to define a named function using def.
- Functional programming: When working with functions as first-class citizens, such as in map(), filter(), or sorted() functions where a function is passed as an argument.
What is key lambda in Python?
The “key” parameter in Python functions like sorted() or max() allows specifying a function to be used for custom sorting or comparison. Lambda functions are often used here to define a key based on which the sorting or comparison is performed.
For example, using sorted() with a lambda function to sort a list of tuples based on the second element:
data = [(1, 'apple'), (3, 'banana'), (2, 'orange')]
sorted_data = sorted(data, key=lambda x: x[1])
print(sorted_data) # Output: [(1, 'apple'), (3, 'banana'), (2, 'orange')]
Please Login to comment...