2
0
mirror of https://github.com/chubin/cheat.sheets synced 2024-11-19 03:25:44 +00:00

Added python lambda

This commit is contained in:
lepatrick714 2017-07-18 21:09:49 -07:00
parent 59a70b33bf
commit b44697ec5c

43
sheets/_python/lambda Normal file
View File

@ -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]