Lambdas are one line functions. They are also known as anonymous functions in some other languages.
Blueprint
lambda argument: manipulate(argument)
Example
add = lambda x, y: x + y
print(add(3, 5))
# Output: 8
List sorting
a = [(1, 2), (4, 1), (9, 10), (13, -3)]
a.sort(key=lambda x: x[1])
print a
# Output: [(13, -3), (4, 1), (1, 2), (9, 10)]
Filter with Lambdas
number_list = range(-5, 5) less_than_zero = list(filter(lambda x: x < 0, number_list)) print less_than_zero # Output: [-5, -4, -3, -2, -1]
Reduce with Lambdas
from functools import reduce
product = reduce((lambda x, y: x * y), [1, 2, 3, 4])
# Output: 24
No comments:
Post a Comment