''' lambdas.py demonstrates some functional programming features''' from functools import reduce ''' lambdas are one line anonymous functions ''' g = lambda x : x+5 ''' filters are functions that return True or False ''' def even(x): if x % 2 == 0 : return True else: return False def cube(x,y): return y**x print(g(8)) # calling the lambda function mylist = [] ''' filters can be applied across a range of values. It returns a list of values for which the filter returned true. ''' myfilter = filter(even, range(0,47)) ''' Iterate through the list to get the filtered values ''' mylist = [x for x in myfilter ] print (mylist) ''' map applies a function across a range of values. Similar to filter, except maps can apply any function, where filters only take functions that return True or False ''' mymap = map(cube, range(0,15), range(0,5)) mylist = [x for x in mymap] print(mylist) def mult(x,y): return x*y ''' A reduce function applies the function across the range, taking the first 2 values the first time, and then applies the result of the operation with every subsequent value, one at a time. ''' print(reduce(mult, range(2,10)))