From b44697ec5c4d49ff1cf8bf83b826296e653881ac Mon Sep 17 00:00:00 2001 From: lepatrick714 Date: Tue, 18 Jul 2017 21:09:49 -0700 Subject: [PATCH] Added python lambda --- sheets/_python/lambda | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 sheets/_python/lambda diff --git a/sheets/_python/lambda b/sheets/_python/lambda new file mode 100644 index 0000000..157134a --- /dev/null +++ b/sheets/_python/lambda @@ -0,0 +1,43 @@ +# Lambda are anonymous functions in Python by using the keyword lambda +# Therefore they are not bound to a name + +# Simple Lambda Function +a = lambda para1: para1 + 40 + +print g(2) # Outputs 42 + + +# Lambda Functions Inside Real Functions +def subtract_func(n) : + return lambda x: x - n + +a = subtract_func(1) # Sets n to 1 for a +b = subtract_func(2) # Sets n to 2 for b + +print( a(-4) ) # Outputs -5 ( -5 = -4 - 1 ) +print( a(-2) ) # Outputs -4 ( -4 = -2 - 2 ) + + +# Multiple Parameters +f = lambda x, y : x + y + +print( f(1,1) ) # Outputs 2 ( 1 + 1 ) + + +# map() Functions +a = [1, 2, 3, 4, 5] +b = [1, 2, 3, 4, 5] + +r = map( lambda x,y : x+y, a,b ) # map() will return an iterator +r_list = list( r ) # listify r + +print(r_list) # prints [2, 4, 6, 8, 10] + + +# filter() Functions +# Program to filter out only the even items from a list +my_list = [1, 5, 4, 6, 8, 11, 3, 12] + +new_list = list(filter(lambda x: (x%2 == 0) , my_list)) + +print(new_list) # Output: [4, 6, 8, 12]