Lambda function is used to create a small anonymous function. Lambda is a powerful python function with some limited capabilities. Lambda function can accept any number of elements as input but only one expression is evaluated and returned.
Why Use Lambda Function?
Lambda function is preffered for writing single line function instead of using normal functions. For writing a normal function we need to use def keyword to define a function and return keyword is used to return value from function.
Lambda function requires a lambda keyword to define a lambda function and don’t need any keyword for return values from lambda functions.
Syntax
For single Input
lambda <argument>: <Calculation or Evaluation>
For Multiple Input
lambda <argument1,argument2,argument3..>: <Calculation or Evaluation>
Examples
Addition of one Variable
lambda a : a+10
Above function accepts onr variable "a" and returns it after adding 10 into it.
Addition of Two Variables
lambda a,b : a+b
Above function accepts two variables "a" and "b" and return addition of a and b.
1. Addition of one Variable
Using Normal Function
# Create a Function To Add 10 To Input Number
def Add(a):
return a+10
result = Add(5)
print(result)
output:
15
Using Lambda Function
# Create a Lambda Function
Add = lambda a : a+10
result = Add(5)
print(result)
Output:
15
2. Addition of Two Variables
Using Normal Function
# Create a Function to accept two number and returns addition
def Add(a,b):
return a+b
result = Add(5,6)
print(result)
output:
11
Using Lambda Function
Add = lambda a,b : a+b
result = Add(5,6)
print(result)
Output:
11
3. Addition of Two numbers List
# Define Two Lists
lst1 = [1,2,3,4]
lst2 = [5,6,7,8]
# Use of Multiple Parameter as input
Addition = map(lambda a,b:a+b,lst1,lst2)
print(f" List 1 : {lst1} \n List 2 : {lst2}")
# Convert mapped object to list
final_result = list(Addition)
print(f" Addition of List1 and List2 : {final_result}")
Output:
List 1 : [1, 2, 3, 4]
List 2 : [5, 6, 7, 8]
Addition of List1 and List2 : [6, 8, 10, 12]
Lambda Function can be used with map, filter, reduce python built-in functions
Note: Lambda Function has some limited capabilities such as only one expression can be evaluated.
map is used to apply a specific function on every element of an iterable object such as list, tuple, strings etc.
Map returns a mapped object after applying function to every element from iterable object. Map can be used with both normal functions or lambda function.
Syntax
map(func, *iterables)
Where
func : Normal function or a Lambda function.
iterbales: Any iterable Object such as list, string, tuple etc.
Examples
We are going to apply map() on multiple examples. And compare examples with both user defined function and a lambda function.
1. Add 5 to every element of list using (user defined function)
# add 5 to given input elements
def Add(a):
return a+5
# A Sample list
lst = [1,2,3,4]
# Apply Add Function to lst with map()
result = list(map(Add,lst))
print(f" Result: {result}")
Result: [5,7,8,9]
Add 5 to every list elements using lambda function.
# A Sample list
lst = [1,2,3,4]
# Apply Add Function to lst with map()
result = map(lambda a : a+5,lst)
final_result = list(result)
print(f"Result: {result}")
output:
Result: [6,7,8,9]
2. Convert a string numbers into int numbers in lst.
# A Sample strings numbers list
lst = ['1','2','3','4']
# Conversion into int
result = map(int,lst)
# Type cast map object to list
final_result = list(result)
print(f"Int List(After Conversion): {final_result}")
Output:
Int List(After Conversion) : [1, 2, 3, 4]
If we check the datatype of list elements before then after then we get following result.
# Original List (Datatype)
type(lst[0])
<class 'str'>
# Converted List (Datatype)
type(final_result[0])
<class 'int'>
Filter is used to filter out records from an iterable object based on condition evaluated from a function. It function is applicable to every element of an iterable object.
Filter added the element to the final list only if applied function returns True Otherwise that element is excluded.
Syntax
filter(function or None, iterable)
Where
function : any user defined normal function or lambda function. iterable : any iterable Object such as list, tuple, strings etc.
Example: 1
Filter Even numbers from given input list using filter.
# Define a List
lst = [1,2,3,4,5,6,7,8]
# Filter out odd Numbers
odd_numbers = filter(lambda a:a%2!=0,lst)
# Filter out Even Numbers
even_numbers = filter(lambda a:a%2==0,lst)
print(f" List : {lst}")
# Convert mapped object to list
odd_result = list(odd_numbers)
even_result = list(even_numbers)
print(f"Filtered List(Odd) : {odd_result}")
print(f"Filtered List(Even) : {even_result}")
Output:
List : [1, 2, 3, 4, 5, 6, 7, 8]
Filtered List(Odd) : [1, 3, 5, 7]
Filtered List(even) : [2, 4, 6, 8]
Example: 2
Filter Uppercase letters using filter.
# Define a string
text = "PyThOn"
# Filter out Capital Letters
uppercase_alpha = filter(lambda a:a.isupper(),text)
# Convert mapped object to list
final_result = list(uppercase_alpha)
print(f"text : {text}")
print(f"Uppercase Letters : {final_result}")
Output:
text : PyThOn
Uppercase Letters : ['P', 'T', 'O']
Reduce function is not a part of python built-in function you need to import it from functools.It is used to reduce an iterable object to a single value by combining elements via a applied function.
Syntax
from functools import reduce
result = reduce(function, iterable)
Where
function : Any lambda or normal user defined function.
sequence : any sequence iterable list
Example
# Define a list
lst = [1,2,3,4,5]
# Import reduce from functools
from functools import reduce
result = reduce(lambda a,b :a+b,lst)
print(f"Addition of All Elements in List is : {result}")
Output:
Addition of All Elements in Lst1 is : 15
# without reduce
val = ((((1+2)+3)+4)+5)
print(val)
15
Self Practice exercise
1. Write a Program using lambda to calculate square of given user input radius.
2. Write a Program using lambda to multiply three elements.
3. Write a Program For Addition of Following Lists.
Lst1 = [0,1,2]
Lst2 = ["3","4","5"]
4. Write a Program to find out numbers from range(1,121) divisible by 3,
5. Write a Program to calculate sum of odd numbers (1,100)
6. Write a program to convert List element to int
Lst = ["3","4","5"]
If you have any questions or suggestions in the comments section below, follow us on social media for more such articles.
Thanks for reading!