As you know lambda expression is used to create a function without any name. We will see different Python lambda example program codes in this tutorial.
Syntax
lambda argument(s): expression
Python lambda examples
Simple example code.
Single argument adding example
Execute a lambda function on a single value.
res = lambda a: a + 10
print(res(10))
Output: 20
Multiple arguments Multipicaiton example
res = lambda a, b: a * b
print(res(10, 5))
Output: 50
Return Lambda Functions example
Double the given number.
def my_func(n):
return lambda a: a * n
double_it = my_func(2)
print(double_it(5))
Output: 10
Example filter List using Lambda Functions
Using the filter() method to get the even from the given list.
list_1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
res = filter(lambda x: x % 2 == 0, list_1)
print(list(res))
Output:
Using map() function: Get cubes for every number in the list.
list_1 = [1, 2, 3, 4, 5]
cubed = map(lambda x: pow(x, 3), list_1)
print(list(cubed))
Output: [1, 8, 27, 64, 125]
Python Lambda example with apply() function by Pandas
Get the current age of each member.
import pandas as pd
df = pd.DataFrame({
'Name': ['Annie', 'John', 'Tim', 'Mike'],
'Status': ['Father', 'Mother', 'Son', 'Daughter'],
'Birthyear': [1972, 1964, 2001, 2006],
})
df['age'] = df['Birthyear'].apply(lambda x: 2021 - x)
print(df)
Output:
Python Lambda Function with if-else
Lambda function to check if a given value is from 10 to 20
test = lambda x: True if (x > 10 and x < 20) else False
print((test(10)))
Output: False
Using lambda() Function with reduce()
from functools import reduce
li = [100, 200, 300]
sum = reduce((lambda x, y: x + y), li)
print(sum)
Output: 600
Do comment if you have any doubts or suggestions on this Python example code.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.