Lambda: Anomymous Functions

Definition

Lambda functions are defined by lambda keyword, which could only have one expression but multiple arguments. We can assign the lambda function to any variable so that we can use it as a function. More generally, we use lambda together with map, reduce or filter.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
'''
lambda [arguments] : [expression]
'''
# zero argument
a = lambda : print('hello')
# one argument
b = lambda x : x**2
# multiple arguments
c = lambda x, y : x + y
a()
print(b(2))
print(c(2, 3))
'''
hello
4
5
'''

Usage

In addition to the basic usage above, there are 4 ways to make use of lambda in general.

Functions nested lambda

1
2
3
4
5
6
7
def new_func(x):
return lambda y : x + y
t = new_func(3)
print(t(3))
'''
6
'''

Anomymous functions are also functions and they have their own scope, because of which, anomymous function will use variables of enclosing function or global variables once they can't find the specific variable in the local scope.

map and lambda

map funtion makes use the idea of SIMD. It maps a certain function to all the elements of input list and return a iterator which can be turned to list using list().

1
2
3
4
5
6
7
8
'''
map(func_to_apply, iterable)
'''
a = [1, 2, 3, 4, 5]
print(list(map(lambda x : x**2, a)))
'''
[1, 4, 9, 16, 25]
'''

map can also deal with two or more lists as long as the length of lists is the same and the function supports more than one arguments:

1
2
3
4
5
6
7
for i in map(lambda x, y : x + y, [1, 2, 3], [4, 5, 6]):
print(i)
'''
5
7
9
'''

What's more, the element of list could even be function:

1
2
3
4
5
6
7
8
9
10
11
12
13
def sq(x):
return x**2
def doub(x):
return 2 * x
for i in range(5):
print(list(map(lambda x : x(i), [sq, doub])))
'''
[0, 0]
[1, 2]
[4, 4]
[9, 6]
[16, 8]
'''

reduce and lambda

reduce firstly passes the first two elements of list to the function. Then, take the result of function as the new first argument and pass it to the function with the third element of list and so on until the last element:

1
2
3
4
5
6
7
8
9
'''
reduce(func, iterable)
'''
from functools import reduce
a = [1, 2, 3, 4, 5]
print(reduce(lambda x, y : x + y, a)) # equal to 1 + 2 + 3 + 4 + 5
'''
15
'''

The element of list could also be function.

filter and lambda

filter returns a iterator that contains elements in the input_list that match the criteria of the function:

1
2
3
4
5
6
7
8
'''
filter(func, iterable)
'''
a = filter(lambda x: x % 2 == 0, range(10)) # get even number
print(list(a))
'''
[0, 2, 4, 6, 8]
'''

filter is easily replaced by for or for if comprehension:

1
2
3
4
5
6
7
8
a = [i for i in range(10)]
print(a)
a = [i for i in range(10) if i % 2 == 0]
print(a)
'''
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 2, 4, 6, 8]
'''