Unit 1 CHP 3
Unit 1 CHP 3
1. Python Lambda Functions are anonymous function means that the function is without
a name.
2. def keyword is used to define a normal function in Python. Similarly,
the lambda keyword is used to define an anonymous function in python.
3. 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.
4. Example:
a. Lambda function to print hello world
>>>a = lambda : print('Hello World')
we have defined a lambda function and assigned it to the variable named a
To execute this lambda function, we need to call it. Here's how we can call the
lambda function
# call the lambda
>>>a()
The lambda function above simply prints the text 'Hello World'.
Note: This lambda function doesn't have any arguments
b. lambda Function with an Argument
lambda function that accepts name of the user as an argument and print it
# lambda that accepts one argument
a = lambda name : print('Hey there,', name)
# lambda call
a('John')
c. Lambda functions with multiple arguments
x = lambda a, b : a * b
print(x(5, 6))
d. Area of circle using lambda function
import math
area = lambda r : math.pi*r*r
print(area(5.1))
c. Transform all elements of a list to upper case using lambda and map()
function
animals = ['dog', 'cat', 'parrot', 'rabbit']
uppered_animals = list(map(lambda animal: animal.upper(), animals))
print(uppered_animals)
d. Multiple arguments
# Create two lists with numbers
numbers1 = [2, 4, 5, 6, 3]
numbers2 = [1, 3, 2, 2, 4]
# Create lambda function that takes two arguments
add_fun = lambda x, y: x+y
add_result = list(map(add_fun, numbers1, numbers2))
print(add_result)
# Output:
# [3, 7, 7, 8, 7]
Here, the lambda function takes two arguments x, y and adds their
values. The map() function applies this lambda function to each
item of the numbers1 & numbers2 lists, and the result is a new
iterator containing the sum of both numbers element -wise.
b. Find the maximum element in a list using lambda and reduce() function
import functools
# initializing list
lis = [1, 3, 5, 6, 2, ]
# using reduce to compute maximum element from list
print("The maximum element of the list is : ", end="")
print(functools.reduce(lambda a, b: a if a > b else b, lis))