lambda
Before introducing the following three advanced functions, let’s focus on lambda. Lambda is a kind of anonymous function, which is widely used in functional programming. Let’s view some examples.
def sum1(x,y):
return x+y
print(1,2) # res: 3
sum2 = lambda x,y: x+y
print(1,2) # res: 3
The above sum1 and sum2 have same function. They both return the sum of two arguments.
1. filter(func, seqs)
2. map(func, seqs)
3. reduce(function, seqs)
EXAMPLE
print(list(filter(lambda x: x % 2 == 1, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])))
print(list(map(lambda x: pow(x,2),[1, 2, 3, 4, 5, 6, 7, 8, 9, 10])))
print(reduce(lambda x,y:x+y,[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
EXAMPLE RESULT:
[1, 3, 5, 7, 9]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
55