Lambda or anonymous functions are small functions that can take any number of arguments, but can only have one expression. These functions are defined without a name.
While normal functions are defined using the def keyword in Python, anonymous functions are defined using the lambda keyword.
increase = lambda x: x+1
simpleSum = lambda x,y: x+y
squareSum = lambda x,y: x*x + y*y
"""
1+1 is 2
2^2 + 3^2 is 5
3^2 + 5^2 is 41
"""
print("1+1 is", increase(1))
print("2^2 + 3^2 is", simpleSum(2,3))
print("4^2 + 5^2 is", squareSum(4,5))
The power of lambda is better shown when you use them as the return of another function, where you can finally give a name to the function.
def power(n):
return lambda x: x**n
square = power(2)
cube = power(5)
sqrt = power(0.5)
"""
6^2 is 36
7^3 is 16807
8^(1/2) is 2.8284271247461903
9^(1/2) is 3.0
"""
print("6^2 is", square(6))
print("7^3 is", cube(7))
print("8^(1/2) is", sqrt(8))
print("9^(1/2) is", sqrt(9))
The filter() function in Python takes in a function and a list as arguments. The function is called with all the items in the list and a new list is returned which contains items for which the lambda function evaluates to True.
fibonacci = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
scientists_IQ = [ ['Copernicus', 160],
['Einstein', 160],
['Galileo', 185],
['Descartes', 180],
['Darwin', 165],
['Kant', 175]
]
filter1 = list(filter(lambda x: (x%2 == 0), fibonacci))
filter2 = list(filter(lambda x: (x[1] > 170), scientists_IQ))
"""
[2, 8, 34]
[['Galileo', 185], ['Descartes', 180], ['Kant', 175]]
"""
print(filter1)
print(filter2)
The map() function in Python takes in a function and a list. The function is called with all the items in the list and a new list is returned which contains items returned by the lambda function for each item.
fibonacci = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
sqr_fibonacci = list(map(lambda x: x*x , fibonacci))
# [1, 1, 4, 9, 25, 64, 169, 441, 1156, 3025]
print(sqr_fibonacci)
You can also sort the elements inside of a list/tuple by a lambda funcion, where you can write a function based on the elements inside of each item of the original list/tuple. This application is really useful.
scientists_IQ = [ ['Copernicus', 160],
['Einstein', 160],
['Galileo', 185],
['Descartes', 180],
['Darwin', 165],
['Kant', 175]
]
byIQ = sorted(scientists_IQ, key = lambda x: x[1], reverse = True)
byName = sorted(scientists_IQ, key = lambda x: x[0])
"""
Sorted by IQ:
Galileo
Descartes
Kant
Darwin
Copernicus
Einstein
Sorted by name:
Copernicus
Darwin
Descartes
Einstein
Galileo
Kant
"""
print("Sorted by IQ:")
for name, iq in byIQ:
print(name)
print("\nSorted by name:")
for name, iq in byName:
print(name)