Lambda Functions |
lambda functions are anonymous functions the lambda keyword is used to define an anonymous function below is a lambda function named upper which takes a string as its argument and converts it to uppercase using the upper() method s = 'n4jvp' upper = lambda string: string.upper() print(upper(s)) |
Lambda Function Syntax |
a function can have any number of arguments but only one expression which is evaluated and returned use lambda functions wherever function objects are required lambda arguments : expression |
Use of Lambda Function |
condition checking using lambda function
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)) |
Practical Uses of Python lambda function |
Lambda Function with List Comprehension
on each iteration inside the list comprehension, a new lambda function with a default argument of x is
created(where x is the current item in the iteration)inside the for loop calling the same function object having the default argument using item() and get the desired value is_even_list stores the list of lambda function objects is_even_list = [lambda arg=x: arg * 10 for x in range(1, 5)] for item in is_even_list: print(item()) Lambda Function with if-else
the Max lambda function to find the maximum of two integers
Max = lambda a, b : a if(a > b) else b print(Max(1, 2)) Lambda with Multiple Statements
Lambda functions do not allow multiple statementscan create two lambda functions and then call the other lambda function as a parameter to the first function a = [[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(a, sortList) print(res) |
Using lambda() Function with filter() |
Filter out all odd numbers using filter() and lambda function
the filter() function takes a function and a list as argumentsthe lambda function below returns True lambda x: (x % 2 != 0)causes filter method to add x to its internal list when a has been iterated final_list is populated filter out all the elements of a sequence 'sequence' for which the function returns True code below returns the odd numbers from an input list a = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61] final_list = list(filter(lambda x: (x % 2 != 0), a)) print(final_list) Filter all people having age more than 18, using lambda and filter() function
code filters a list of ages and extracts the ages of adults (ages greater than 18) prints the list of adult ages the output displays the ages of individuals who are 18 years or older ages = [13, 90, 17, 59, 21, 60, 5] adults = list(filter(lambda age: age > 18, ages)) print(adults) |
Using lambda() Function with map |
the map() function takes in a function and a list as an argument the function is called with a lambda function and a list a new list is returned which contains all the lambda-modified items returned by that function for each item 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' functionthen prints the new list with the doubled elements li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61] final_list = list(map(lambda x: x*2, li)) print(final_list) 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' functionthen prints the list with the animal names in uppercase animals = ['dog', 'cat', 'parrot', 'rabbit'] uppered_animals = list(map(lambda animal: animal.upper(), animals)) print(uppered_animals)animals = ['dog', 'cat', 'parrot', 'rabbit'] uppered_animals = list(map(lambda animal: animal.upper(), animals)) print(uppered_animals) |
Using lambda() Function with reduce() |
the reduce() function takes in a function and a list as an argument the function is called with a lambda function and an iterable a new reduced result is returned 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 it imports 'reduce' and defines a list then applies a lambda function that adds two elements at a time prints the sum of all elements in the list output displays the computed sum from functools import reduce a = [5, 8, 10, 20, 50, 100] total = reduce((lambda x, y: x + y), a) print(total) Find the maximum element in a list using lambda and reduce() function
the code uses the 'reduce' function to find the maximum element in a listthen prints the maximum element import functools a = [1, 3, 5, 6, 2, ] print("The maximum element of the list is : ", end="") print(functools.reduce(lambda i, j: i if i > j else j, a)) |