21
NovLambda Function in Python with Examples (Full Tutorial)
Python Lambda Functions
In this Python tutorial, we'll get into functions in Python covering aspects like the syntax of Python Lambda Functions, an example of Python Lambda Function, and the application of Lambda Function in Python.
Elaborate Lambda Function in Python?
- A kind of anonymous function is called a lambda function.
- Although a lambda function can only have one expression.
- It can have an unlimited number of parameters.
Python Lambda Function Syntax:
lambda arguments : expression
Python Lambda Function Example
str1 = 'Scholarhat'
upper = lambda string: string.upper()
print(upper(str1))
Output
SCHOLARHAT
Practical Uses of lambda function in Python
In this section, we will learn various uses of the Lambda Function in Python
1. Condition Checking Using Python 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))
Output
Int formatting: 1.000000e+06
float formatting: 999,999.79
Explanation:
Here we have done Condition Checking Using the Python lambda function. In the above program, the ‘format_numric’ calls the lambda function, and the num is passed as a parameter to perform operations.2. List Comprehension using Python Lambda Function
We are generating a new lambda function with a default argument of x (the current item in the iteration) on each iteration within the list comprehension. Afterwards, we use item() to execute the same function object with the default parameter later on in the for loop, obtaining the required value. Consequently, the list of lambda function objects is stored in is_even_list.
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
3. if-else using Python Lambda Function
Max = lambda a, b : a if(a > b) else b
print(Max(4, 10))
Output
10
4. filter() Using lambda() Function
- Python's filter() function accepts two arguments: a list and a function.
- With this, you can effectively filter out any element of a "sequence" that the function returns True.
- This is a little software that takes an input list and returns the odd numbers:
- Use the filter() and lambda functions to eliminate all odd numbers.
- If x is not even, lambda x: (x % 2!= 0) yields True; otherwise, it returns False. All odd numbers that produced False are eliminated since filter() only retains elements where it returns True.
que = [5, 7, 33, 97, 54, 64, 77, 23, 74, 62]
final_list = list(filter(lambda x: (x % 2 != 0), que))
print(final_list)
Output
[5, 7, 33, 97, 77, 23]
5. Lambda Function using Multiple Statements
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]
6. map() with Using lambda() Function
- Python's map() function accepts two arguments: a list and a function.
- When a lambda function and a list are passed to the function, a new list containing every lambda-modified item that the function returned for each item is returned. For instance:
- Use the lambda and map() functions to multiply each entry in a list by two.
- The lambda function and the "map" function are used in the code to duplicate every element in a list.
- The updated list with the doubled elements is then printed. Each element from the original list is multiplied by two and displayed in the output.
que = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61]
final_list = list(map(lambda x: x*3, que))
print(final_list)
Output
[15, 21, 66, 291, 162, 186, 231, 69, 219, 183]
Convert elements to upper case using lambda and map() function
employess = ['daksh', 'heral', 'manish', 'reva']
uppered_employees = list(map(lambda employee: employee.upper(), employess))
print(uppered_employees)
Output
['DAKSH', 'HERAL', 'MANISH', 'REVA']
Explanation:
Here, The program converts a list of employee names to uppercase using a lambda function and the ‘map' function and then it prints the list with the employee names in uppercase. The output shows the employee names in all uppercase letters.For more in-depth knowledge about it. Click Below7. The reduce() using lambda() Function
A list's sum of every item using the lambda and reduce() functions
from demo import reduce
que = [33, 11, 50, 80, 50, 100]
sum = reduce((lambda a, b: a + b), que)
print(sum)
Output
324
Explanation
The program performs the sum of elements in a list using the ‘reduce' function from the ‘demo' 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.
Difference Between Lambda functions and def defined function
def cube(y):
return y*y*y
lambda_cube = lambda y: y*y*y
print("Using function defined with `def` keyword, cube:", cube(6))
print("Using lambda function, cube:", lambda_cube(6))
Output
Using function defined with `def` keyword, cube: 216
Using lambda function, cube: 216