2
0
mirror of https://github.com/chubin/cheat.sheets synced 2024-11-03 15:40:17 +00:00
cheat.sheets/sheets/_python/lambda

39 lines
1.1 KiB
Plaintext
Raw Normal View History

2017-07-19 04:09:49 +00:00
# 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
2017-07-19 05:34:01 +00:00
#
2017-07-19 04:09:49 +00:00
print g(2) # Outputs 42
# Lambda Functions Inside Real Functions
def subtract_func(n) :
return lambda x: x - n
2017-07-19 05:34:01 +00:00
#
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 )
# Lambda Function with Multiple Parameters
2017-07-19 04:09:49 +00:00
f = lambda x, y : x + y
2017-07-19 05:34:01 +00:00
#
print( f(1,1) ) # Outputs 2 ( 1 + 1 )
2017-07-19 04:09:49 +00:00
2017-07-19 05:34:01 +00:00
# map() + lambda functions
2017-07-19 04:09:49 +00:00
a = [1, 2, 3, 4, 5]
b = [1, 2, 3, 4, 5]
2017-07-19 05:34:01 +00:00
#
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]
2017-07-19 04:09:49 +00:00
2017-07-19 05:34:01 +00:00
# filter() + lambda functions
2017-07-19 04:09:49 +00:00
# Program to filter out only the even items from a list
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
2017-07-19 05:34:01 +00:00
#
2017-07-19 04:09:49 +00:00
new_list = list(filter(lambda x: (x%2 == 0) , my_list))
2017-07-19 05:34:01 +00:00
#
print(new_list) # Output: [4, 6, 8, 12]